Example usage for org.apache.http.client.methods CloseableHttpResponse getEntity

List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse getEntity.

Prototype

HttpEntity getEntity();

Source Link

Usage

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

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

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet httpget = new HttpGet("/");
        httpget.setConfig(config);

        System.out.println("Executing request " + httpget.getRequestLine() + " to " + target + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(target, httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.http.my.ClientFormLogin.java

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

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            System.out.println(response.getStatusLine());
            if (status >= 200 && status < 303) {
                HttpEntity entity = response.getEntity();

                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }//from  w  ww .j  ava2 s  .  c o m
        }

    };

    BasicCookieStore cookieStore = new BasicCookieStore();
    //        
    //        BasicClientCookie cookieJSESSIONID = new BasicClientCookie("JSESSIONID", "3FD927DC6911B719E4492E7473897FBA");
    //        cookieJSESSIONID.setVersion(0);
    //        cookieJSESSIONID.setDomain("218.75.79.230");
    //        cookieJSESSIONID.setPath("/");
    //        System.out.println("Initial set of cookies:");
    //        cookieStore.addCookie(cookieJSESSIONID);

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    // HttpProtocolParams.setUserAgent(httpclient.getParams(), "Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)");

    try {

        // HttpPost httpost = new HttpPost("http://localhost:8081/cring/jsp/user/userLogin.do?method=login");
        HttpPost loginpost = new HttpPost("http://134.96.41.47/ecommunications_chs/start.swe");
        //HttpGet loginGet = new HttpGet("http://134.96.41.47/ecommunications_chs/start.swe");
        // HttpGet loginGet = new HttpGet("http://www.baidu.com");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("SWEUserName", "nili"));
        nvps.add(new BasicNameValuePair("SWEPassword", "nili7788"));
        nvps.add(new BasicNameValuePair("SWEFo", "SWEEntryForm"));
        nvps.add(new BasicNameValuePair("SWENeedContext", "false"));
        nvps.add(new BasicNameValuePair("SWECmd", "ExecuteLogin"));
        nvps.add(new BasicNameValuePair("W", "t"));
        nvps.add(new BasicNameValuePair("SWEC", "0"));
        nvps.add(new BasicNameValuePair("SWEBID", "-1"));
        nvps.add(new BasicNameValuePair("SWETS", "1385712482625"));

        /**
         *  SWEUserName:111111
        SWEPassword:222222
        SWEFo:SWEEntryForm
        SWENeedContext:false
        SWECmd:ExecuteLogin
        W:t
        SWESPNR:
        SWESPNH:
        SWEH:
        SWEC:0
        SWEW:
        SWEBID:-1
        SWETS:1385712482625
        SWEWN:
         */
        loginpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        //            CloseableHttpResponse response =  httpclient.execute(loginpost);
        // HttpEntity httpEntity =  response.getEntity();
        CloseableHttpResponse responseGet = httpclient.execute(loginpost);
        HttpEntity httpEntityGet = responseGet.getEntity();
        System.out.println("statusLine: " + responseGet.getStatusLine());
        System.out.println("ContentType: " + httpEntityGet.getContentType());
        System.out.println("ContentLength: " + httpEntityGet.getContentLength());

        //  httpEntityGet.get
        System.out.println("loginGet: " + EntityUtils.toString(httpEntityGet));
        /* try {
                
        System.out.println("Post logon cookies:");
        List<Cookie> cookies = cookieStore.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 modifypost = new HttpPost("http://localhost:8081/cring/jsp/user/corpUserController.do?method=modifyPwd");
        List <NameValuePair> modifynvps = new ArrayList <NameValuePair>();
        modifynvps.add(new BasicNameValuePair("newPwd","111111"));
        modifypost.setEntity(new UrlEncodedFormEntity(modifynvps, Consts.UTF_8));
                    
        CloseableHttpResponse modifyresponse = httpclient.execute(modifypost);
            System.out.println("modifyresponse : "+modifyresponse.getStatusLine()); 
                
                
                
         } finally {
        //response2.close();
         }*/
    } finally {
        httpclient.close();
    }
}

From source file:myexamples.MyExamples.java

public static void main(String[] args) throws Exception {
    String tweetString = "";
    RefEntity refEntity = new RefEntity();
    String refEntityString = gson.toJson(refEntity);
    httpclient = HttpClients.createDefault();
    try {/*from  ww  w .  ja  va  2 s  .  c  om*/
        //getExample();    
        tweetString = getTweet();
        StringEntity stringEntity = new StringEntity(refEntityString);
        HttpPost httppost = new HttpPost("http://localhost:9200/referenzer/reference");
        httppost.setEntity(stringEntity);
        CloseableHttpResponse response1 = httpclient.execute(httppost);
        System.out.println("responseStatus=" + response1.getStatusLine());
        PostResponseEntity pRE = gson.fromJson(EntityUtils.toString(response1.getEntity()),
                PostResponseEntity.class);
        System.out.println(pRE.toString(1));
        //System.out.println("response="+EntityUtils.toString(response1.getEntity()));
    } finally {
        httpclient.close();
    }

    System.out.println(tweetString);

    Gson gson = new Gson();
    TweetResponse tweetResponse = gson.fromJson(tweetString, TweetResponse.class);
    System.out.println(tweetResponse.toString(1));

    System.out.println(refEntityString);
}

From source file:ClientChunkEncodedPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);//from  w w w .  j a  v a 2  s  .c om
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://localhost/");

        File file = new File(args[0]);

        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1,
                ContentType.APPLICATION_OCTET_STREAM);
        reqEntity.setChunked(true);
        // It may be more appropriate to use FileEntity class in this particular
        // instance but we are using a more generic InputStreamEntity to demonstrate
        // the capability to stream out data from any arbitrary source
        //
        // FileEntity entity = new FileEntity(file, "binary/octet-stream");

        httppost.setEntity(reqEntity);

        System.out.println("Executing request: " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.oocl.euc.ita.test.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*w  ww . j  a v a2s  .  c  o  m*/

        //           HttpPost?
        HttpPost httpPost = new HttpPost("http://localhost:8080/qb-webapp/login");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "Neolarry"));
        nvps.add(new BasicNameValuePair("password", "123456789"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        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();
        }

        HttpGet httpGet = new HttpGet("http://localhost:8080/qb-webapp/api/trainer");
        System.out.println(httpGet.getURI());
        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("get: "+response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            String responseString = "";

            if (entity1 != null) {
                //     
                //                    System.out.println("Response content length: " + entity1.getContentLength());  
                System.out.println(responseString = EntityUtils.toString(entity1));
                // ?                      
            }

            //JsonToObject
            //              JSONArray s = JSONArray.parseArray(responseString);
            //              for (int i = 0; i < s.size(); i++) {
            //                 System.out.println(s.get(i));
            //              }

            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

    } finally {
        httpclient.close();
    }
}

From source file:org.ege.httpclient.ClientAuthentication.java

public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials("alice", "alice"));

    Lookup<AuthSchemeProvider> basicAuthSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC, new BasicSchemeFactory()).build();
    Lookup<AuthSchemeProvider> spnegoAuthSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .setDefaultAuthSchemeRegistry(spnegoAuthSchemeRegistry).build();

    //Lookup<AuthSchemeProvider> authProviders = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.BASIC, new BasicSchemeFactory()).build();
    //Lookup<AuthSchemeProvider> authRegistry = <...>

    //HttpClientContext context = HttpClientContext.create();
    //context.setCredentialsProvider(credsProvider);
    //context.setAuthSchemeRegistry(authRegistry);

    try {/*from w  w w .ja  v a2  s. c o  m*/
        HttpGet httpget = new HttpGet("http://lcom501d/hooks/hdr.cgi");

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:demo.example.ClientMultipartFormPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);//w w  w  . jav  a2  s . c  o  m
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(
                "http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");

        FileBody bin = new FileBody(new File(args[0]));
        StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment)
                .build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.orange.ClientExecuteProxy.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//  w ww  .jav a 2 s . c  o  m
        HttpHost target = new HttpHost("httpbin.org", 443, "https");
        HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet request = new HttpGet("/");
        request.setConfig(config);

        System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(target, request);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.renren.ntc.sg.util.wxpay.https.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(
            new File("/Users/allenz/Downloads/wx_cert/apiclient_cert.p12"));
    try {/* w  w  w.j av  a2  s.  c  o m*/
        keyStore.load(instream, Constants.mch_id.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, Constants.mch_id.toCharArray())
            .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 {

        HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers");
        System.out.println("executing request" + post.getRequestLine());

        String openid = "oQfDLjmZD7Lgynv6vuoBlWXUY_ic";
        String nonce_str = Sha1Util.getNonceStr();
        String orderId = SUtils.getOrderId();
        String re_user_name = "?";
        String amount = "1";
        String desc = "";
        String spbill_create_ip = "123.56.102.224";

        String txt = TXT.replace("{mch_appid}", Constants.mch_appid);
        txt = txt.replace("{mchid}", Constants.mch_id);
        txt = txt.replace("{openid}", openid);
        txt = txt.replace("{nonce_str}", nonce_str);
        txt = txt.replace("{partner_trade_no}", orderId);
        txt = txt.replace("{check_name}", "FORCE_CHECK");
        txt = txt.replace("{re_user_name}", re_user_name);
        txt = txt.replace("{amount}", amount);
        txt = txt.replace("{desc}", desc);
        txt = txt.replace("{spbill_create_ip}", spbill_create_ip);

        SortedMap<String, String> map = new TreeMap<String, String>();
        map.put("mch_appid", Constants.mch_appid);
        map.put("mchid", Constants.mch_id);
        map.put("openid", openid);
        map.put("nonce_str", nonce_str);
        map.put("partner_trade_no", orderId);
        //FORCE_CHECK| OPTION_CHECK | NO_CHECK
        map.put("check_name", "OPTION_CHECK");
        map.put("re_user_name", re_user_name);
        map.put("amount", amount);
        map.put("desc", desc);
        map.put("spbill_create_ip", spbill_create_ip);

        String sign = SUtils.createSign(map).toUpperCase();
        txt = txt.replace("{sign}", sign);

        post.setEntity(new StringEntity(txt, "utf-8"));

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

            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                StringBuffer sb = new StringBuffer();
                while ((text = bufferedReader.readLine()) != null) {
                    sb.append(text);
                }
                String resp = sb.toString();
                LoggerUtils.getInstance().log(String.format("req %s rec %s", txt, resp));
                if (isOk(resp)) {

                    String payment_no = getValue(resp, "payment_no");
                    LoggerUtils.getInstance()
                            .log(String.format("order %s pay OK   payment_no %s", orderId, payment_no));
                }

            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:demo.example.ClientProxyAuthentication.java

public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 8888),
            new UsernamePasswordCredentials("squid", "squid"));
    credsProvider.setCredentials(new AuthScope("httpbin.org", 80),
            new UsernamePasswordCredentials("user", "passwd"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {/*from w  w w .j  a va  2 s  . c om*/
        HttpHost target = new HttpHost("httpbin.org", 80, "http");
        HttpHost proxy = new HttpHost("localhost", 8888);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet httpget = new HttpGet("/basic-auth/user/passwd");
        httpget.setConfig(config);

        System.out.println("Executing request " + httpget.getRequestLine() + " to " + target + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(target, httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}