Example usage for org.apache.http.util EntityUtils consume

List of usage examples for org.apache.http.util EntityUtils consume

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils consume.

Prototype

public static void consume(HttpEntity httpEntity) throws IOException 

Source Link

Usage

From source file:interoperabilite.webservice.client.ClientExecuteSOCKS.java

public static void main(String[] args) throws Exception {
    Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new MyConnectionSocketFactory()).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
    try {//w  w  w.jav a2 s.  co  m
        InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
        HttpClientContext context = HttpClientContext.create();
        context.setAttribute("socks.address", socksaddr);

        HttpHost target = new HttpHost("httpbin.org", 80, "http");
        HttpGet request = new HttpGet("/");

        System.out.println("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr);
        CloseableHttpResponse response = httpclient.execute(target, request, context);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:myexamples.QuickStart.java

public static void main(String[] args) throws Exception {
    Gson gson = new Gson();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from   w  w w .j  a v  a2 s .c  o m
        HttpGet httpGet = new HttpGet("http://localhost:9200/gb/tweet/9");
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            if (entity1 != null) {
                long len = entity1.getContentLength();
                if (len != -1 && len < 2048) {
                    System.out.println(EntityUtils.toString(entity1));
                } else {
                    System.out.println("entity length=" + len);
                }
            }
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }
        /*
                    HttpPost httpPost = new HttpPost("http://targethost/login");
                    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
                    nvps.add(new BasicNameValuePair("username", "vip"));
                    nvps.add(new BasicNameValuePair("password", "secret"));
                    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
                    CloseableHttpResponse response2 = httpclient.execute(httpPost);
                
                    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
                    } finally {
        response2.close();
                    }
        */ } finally {
        httpclient.close();
    }
}

From source file:ddu.core.httpclient.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    // Trust own CA and all self-signed certs
    KeyStore trustKeyStore = KeyStore.getInstance("JKS");

    // get user password and file input stream
    char[] password = "123456".toCharArray();
    java.io.FileInputStream fis = null;
    try {//from ww w . jav a2  s  . c om
        fis = new java.io.FileInputStream("keyStoreName");
        trustKeyStore.load(fis, password);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustKeyStore, new TrustSelfSignedStrategy())
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet("https://httpbin.org/");

        System.out.println("Executing request " + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.lxf.spider.client.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(new File("my.keystore"));
    try {/*from   w  w w  . j a v a 2 s .c  om*/
        trustStore.load(instream, "nopassword".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet("https://localhost/");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:test.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(new File("D:\\keystore.jks"));
    try {/*from  w  w w . jav  a 2 s  . c om*/
        trustStore.load(instream, "password".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet("https://retail.onlinesbi.com/personal/css/style.css");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.gypsai.ClientFormLogin.java

public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httppostclient = new DefaultHttpClient();
    httppostclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    try {//  w  ww . ja va2s.c om

        String loginUrl = "http://www.cnsfk.com/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes";
        //String loginUrl = "http://renren.com/PLogin.do";

        String testurl = "http://www.baidu.com";
        HttpGet httpget = new HttpGet(testurl);

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        //System.out.println(istostring(entity.getContent()));

        System.out.println("Login form get: " + response.getStatusLine());
        EntityUtils.consume(entity);

        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                //     System.out.println("- " + cookies.get(i).toString());
            }
        }

        HttpPost httpost = new HttpPost(loginUrl);

        String password = MD5.MD5Encode("luom1ng");
        String redirectURL = "http://www.renren.com/home";
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "gypsai@foxmail.com"));
        nvps.add(new BasicNameValuePair("password", password));
        // nvps.add(new BasicNameValuePair("origURL", redirectURL));  
        // nvps.add(new BasicNameValuePair("domain", "renren.com"));  
        //  nvps.add(new BasicNameValuePair("autoLogin", "true"));  
        //  nvps.add(new BasicNameValuePair("formName", ""));  
        //  nvps.add(new BasicNameValuePair("method", ""));  
        //  nvps.add(new BasicNameValuePair("submit", ""));  

        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        httpost.setHeader("User-Agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.28 (KHTML, like Gecko) Chrome/26.0.1397.2 Safari/537.28");

        //posthttpclient
        //DefaultHttpClient httppostclient = new DefaultHttpClient();

        //postheader
        Header[] pm = httpost.getAllHeaders();
        for (Header header : pm) {
            System.out.println("%%%%->" + header.toString());
        }

        //
        response = httppostclient.execute(httpost);

        EntityUtils.consume(response.getEntity());

        doget();
        //
        //

        //httppostclient.getConnectionManager().shutdown();

        //cookie
        List<Cookie> cncookies = httppostclient.getCookieStore().getCookies();
        System.out.println("Post logon cookies:");

        if (cncookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cncookies.size(); i++) {
                System.out.println("- " + cncookies.get(i).getName().toString() + "   ---->"
                        + cncookies.get(i).getValue().toString());
            }
        }

        //
        submit();

        //httpheader
        entity = response.getEntity();
        Header[] m = response.getAllHeaders();
        for (Header header : m) {
            //System.out.println("+++->"+header.toString());
        }
        //System.out.println(response.getAllHeaders());
        System.out.println(entity.getContentEncoding());

        //statusline
        System.out.println("Login form get: " + response.getStatusLine());

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        //  httpclient.getConnectionManager().shutdown();
        //httppostclient.getConnectionManager().shutdown();
    }
}

From source file:com.da.img.ClientFormLogin.java

public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    try {/*  ww w.jav a  2 s.com*/
        HttpGet httpget = new HttpGet("http://www.soraven.info/index.php");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        //System.out.println( EntityUtils.toString(entity));
        System.out.println("Login form get: " + response.getStatusLine());
        EntityUtils.consume(entity);

        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("-1 " + cookies.get(i).toString());
            }
        }

        HttpPost httpost = new HttpPost("http://www.soraven.info/common/include/login.php");
        Header header1 = new BasicHeader("Accept",
                "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,application/msword, */*");
        Header header2 = new BasicHeader("Referer", "http://www.soraven.info/index.php");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("p_userid", "bimohani"));
        nvps.add(new BasicNameValuePair("p_passwd", "cw8904"));
        nvps.add(new BasicNameValuePair("x", "12"));
        nvps.add(new BasicNameValuePair("y", "20"));
        httpost.setHeader(header1);
        httpost.setHeader(header2);
        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        //Thread.sleep(2000);
        response = httpclient.execute(httpost);
        entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());

        System.out.println(EntityUtils.toString(entity));
        EntityUtils.consume(entity);

        System.out.println("Post logon cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("-2 " + cookies.get(i).toString());
            }
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.lxf.spider.client.ClientPreemptiveBasicAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("localhost", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {/*from w  w w.  j  av  a  2s.  co  m*/

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        HttpGet httpget = new HttpGet("/");

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        }
    } finally {
        httpclient.close();
    }
}

From source file:testing01.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String outputFile = "test.html";
    String baseWebSite = "http://www.ettoday.net/news/20130802/250478.htm";
    try {/*w ww . j  a  v  a  2 s  . c o m*/
        //HttpGet httpGet = new HttpGet(baseWebSite + "cat/politic/r");
        HttpGet httpGet = new HttpGet(baseWebSite);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response
        // object
        // to allow the response content to be streamed directly from the
        // network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally
        // clause.
        // Please note that if response content is not fully consumed the
        // underlying
        // connection cannot be safely re-used and will be shut down and
        // discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            String responseString = EntityUtils.toString(entity1, "UTF-8");
            // System.out.println(responseString);
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF8"));
            out.write(responseString);
            out.close();
            EntityUtils.consume(entity1);
            System.out.println(baseWebSite + " output to " + outputFile + " successful");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            response1.close();
        }
        /*
         * HttpPost httpPost = new HttpPost("http://targethost/login"); List
         * <NameValuePair> nvps = new ArrayList <NameValuePair>();
         * nvps.add(new BasicNameValuePair("username", "vip")); nvps.add(new
         * BasicNameValuePair("password", "secret")); httpPost.setEntity(new
         * UrlEncodedFormEntity(nvps)); CloseableHttpResponse response2 =
         * httpclient.execute(httpPost);
         * 
         * try { System.out.println(response2.getStatusLine()); HttpEntity
         * entity2 = response2.getEntity(); // do something useful with the
         * response body // and ensure it is fully consumed
         * EntityUtils.consume(entity2); } finally { response2.close(); }
         */
    } finally {
        httpclient.close();
    }
}

From source file:com.tianya.ClientMultipartFormPost.java

public static void main(String[] args) throws Exception {

    /*/*from w  ww  . ja  v a 2 s . c o  m*/
     if (args.length != 1)  {
    System.out.println("File path not given");
    System.exit(1);
     }
     */

    HttpClient httpclient = new DefaultHttpClient();
    String posturl = "http://letushow.com/submit";

    preGet(httpclient);

    try {
        HttpPost httppost = new HttpPost(posturl);

        FileBody bin = new FileBody(new File("/Users/gypsai/Desktop/letushow/let.gif"));
        StringBody title = new StringBody("let");

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("imgfile", bin);
        reqEntity.addPart("csrf_token", new StringBody(csrf_token));
        reqEntity.addPart("title", title);
        reqEntity.addPart("type", new StringBody("local"));

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            // System.out.println("Response content length: " + resEntity.getContentLength());
            System.out.println(iotostring(response.getEntity().getContent()));
        }
        EntityUtils.consume(resEntity);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
}