List of usage examples for org.apache.http.client.methods CloseableHttpResponse getStatusLine
StatusLine getStatusLine();
From source file:com.wxpay.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(new File("E:/apiclient_cert1.p12")); try {//from w w w . ja va2 s. c om keyStore.load(instream, "1269885501".toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1269885501".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 { HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund"); 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()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String text; while ((text = bufferedReader.readLine()) != null) { System.out.println(text); } } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:com.work.common.demo.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("d:\\googlemap.keystore")); try {//from w w w . j a va 2s. c om trustStore.load(instream, "111111".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://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AIzaSyBR0i9RL44iG8IUx9LcCgxsYOJf6FutQhE"); System.out.println("executing request" + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpHost, 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()); System.out.println(EntityUtils.toString(entity)); } EntityUtils.consume(entity); } 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 {/*from w w w.j a v a 2 s.co 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: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 w w . ja v a 2 s . com } }; 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:cn.jumper.study.http.ClientFormLogin.java
public static void main(String[] args) throws Exception { BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); HttpHost proxy = new HttpHost("192.168.10.3", 8080, "http"); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); try {/*from w w w . j a va 2s . com*/ HttpGet httpget = new HttpGet("http://www.ksf-food.com/admin/Login.asp"); httpget.setConfig(config); CloseableHttpResponse response1 = httpclient.execute(httpget); try { HttpEntity entity = response1.getEntity(); System.out.println("Login form get: " + response1.getStatusLine()); EntityUtils.consume(entity); System.out.println("Initial set of 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()); } } } finally { response1.close(); } String code = ""; try { HttpUriRequest httpgetCode = RequestBuilder.get() .setUri("http://www.ksf-food.com/admin/inc/checkcode.asp").setConfig(config).build(); /* * HttpGet httpgetCode = new HttpGet( * "http://www.qufuev.com/admin/inc/checkcode.asp"); * httpgetCode.setConfig(config); */ System.out.println("Executing request " + httpgetCode.getRequestLine()); System.out.println("========================================================"); System.out.println("==httpget header =="); for (Header header : httpgetCode.getAllHeaders()) { System.out.println(header.getName() + ":" + header.getValue()); } System.out.println("==httpget header =="); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); System.out.println("==respons header =="); for (Header header : response.getAllHeaders()) { System.out.println(header.getName() + ":" + header.getValue()); } System.out.println("==respons header =="); String fileName = System.currentTimeMillis() + ""; DataOutputStream dataOutputStream = new DataOutputStream( new FileOutputStream("d://test//e3//" + fileName + ".jpg")); dataOutputStream.write(EntityUtils.toByteArray(entity)); dataOutputStream.close(); return ImageTest.getAllOcr("d://test//e3//" + fileName + ".jpg"); } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; code = httpclient.execute(httpgetCode, responseHandler); System.out.println("ClientFormLogin.main()-CheckCode:" + code); System.out.println("----------------------------------------"); } catch (IOException e) { e.printStackTrace(); } HttpUriRequest login = RequestBuilder.post() .setUri(new URI("http://www.ksf-food.com/admin/Admin_ChkLogin.asp")) .addParameter("UserName", "username").addParameter("Password", "password") .addParameter("CheckCode", code).setConfig(config).build(); System.out.println("========================================================"); System.out.println("==httpget header =="); for (Header header : login.getAllHeaders()) { System.out.println(header.getName() + ":" + header.getValue()); } CloseableHttpResponse response2 = httpclient.execute(login); try { HttpEntity entity = response2.getEntity(); System.out.println("Login form post: " + response2.getStatusLine()); // EntityUtils.consume(entity); System.out.println("ClientFormLogin.main():\\n" + EntityUtils.toString(entity, "GBK")); 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()); } } } finally { response2.close(); } } finally { httpclient.close(); } }
From source file:com.atlbike.etl.service.ClientFormLogin.java
/** * @param args/*from w ww .ja va 2 s . c o m*/ * @throws Exception */ public static void main(String[] args) throws Exception { String authenticityToken = ""; BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore) .setRedirectStrategy(new LaxRedirectStrategy()).build(); try { HttpGet httpget = new HttpGet("https://atlbike.nationbuilder.com/login"); CloseableHttpResponse response1 = httpclient.execute(httpget); try { HttpEntity entity = response1.getEntity(); System.out.println("Content Length: " + entity.getContentLength()); System.out.println("Login form get: " + response1.getStatusLine()); // EntityUtils.consume(entity); String content = EntityUtils.toString(entity); Document doc = Jsoup.parse(content); Elements metaElements = doc.select("META"); for (Element elem : metaElements) { System.out.println(elem); if (elem.hasAttr("name") && "csrf-token".equals(elem.attr("name"))) { System.out.println("Value: " + elem.attr("content")); authenticityToken = elem.attr("content"); } } System.out.println("Initial set of 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()); } } } finally { response1.close(); } HttpUriRequest login = RequestBuilder.post() .setUri(new URI("https://atlbike.nationbuilder.com/forms/user_sessions")) .addParameter("email_address", "").addParameter("user_session[email]", "email@domain") .addParameter("user_session[password]", "magicCookie") .addParameter("user_session[remember_me]", "1").addParameter("commit", "Sign in with email") .addParameter("authenticity_token", authenticityToken).build(); CloseableHttpResponse response2 = httpclient.execute(login); try { HttpEntity entity = response2.getEntity(); // for (Header h : response2.getAllHeaders()) { // System.out.println(h); // } System.out.println("Content Length: " + entity.getContentLength()); System.out.println("Login form get: " + response2.getStatusLine()); EntityUtils.consume(entity); 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()); } } } finally { response2.close(); } httpget = new HttpGet( // HttpUriRequest file = RequestBuilder // .post() // .setUri(new URI( "https://atlbike.nationbuilder.com/admin/membership_types/14/download"); // .build(); // CloseableHttpResponse response3 = httpclient.execute(file); CloseableHttpResponse response3 = httpclient.execute(httpget); try { HttpEntity entity = response3.getEntity(); System.out.println("Content Length: " + entity.getContentLength()); System.out.println("File Get: " + response3.getStatusLine()); saveEntity(entity); // EntityUtils.consume(entity); System.out.println("Post file get 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()); } } } finally { response3.close(); } } finally { httpclient.close(); } }
From source file:com.luqili.http.ssl.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { String sslKeyStorePath = "/mnt/data2/clientkey/370900.pfx"; String sslKeyStorePassword = "370900"; String sslKeyStoreType = "PKCS12"; // JKS PKCS12 String sslTrustStore = "/mnt/data2/clientkey/PengeSoftOARoot.cer"; String sslTrustStorePassword = ""; String url = "https://123.57.205.217:8082/Service/UpReportInfoServiceSvr.assx/UpReportInfo"; String content = "Token=&CityCodes=370900&CountyCodes=&DealDate=2016-06-16T00:00:00&Reportor=?&NewBusinessArea=1000.88&NewBusinessAmount=9898&NewHouseArea=5000&NewHouseAmount=8000&NewHouseCount=20&OldReportor=?&OldBusinessArea=1234.56&OldBusinessAmount=80000&OldHouseArea=12580&OldHouseAmount=99999&OldHouseCount=100"; // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(new File(sslKeyStorePath), sslKeyStorePassword.toCharArray(), new TrustSelfSignedStrategy()) .loadKeyMaterial(new File(sslKeyStorePath), sslKeyStorePassword.toCharArray(), sslKeyStorePassword.toCharArray()) .build();/*from w w w .j a v a 2 s.c o m*/ // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { HttpPost httppost = new HttpPost(url); System.out.println("Executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, "UTF-8").trim(); if (!"True".toUpperCase().equals(result.toUpperCase())) { System.out.println(result); } } System.out.println(response.getStatusLine()); EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:an.dpr.cyclingresultsapi.ClientExecuteProxy.java
public static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); StringBuilder ret = new StringBuilder(); try {/*from w w w .j a va 2s .c o m*/ //http://cyclingresults-dprsoft.rhcloud.com/rest/competitions/query/20140101,20140601,1,1,UWT // HttpHost target = new HttpHost("cyclingresults-dprsoft.rhcloud.com", 80, "http"); HttpHost proxy = null;// = new HttpHost("proxy.sdc.hp.com", 8080, "http"); HttpHost target = new HttpHost("localhost", 8282, "http"); RequestConfig config = RequestConfig.custom() // .setProxy(proxy) .build(); HttpGet request = new HttpGet("/rest/competitions/query/20130801,20130901,1,1,UWT"); request.setConfig(config); System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy); CloseableHttpResponse response = httpclient.execute(target, request); InputStreamReader isr = new InputStreamReader(response.getEntity().getContent(), "cp1252"); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { ret.append(line); } try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } finally { httpclient.close(); } System.out.println(ret.toString()); }
From source file:com.li.tools.httpclient.util.ClientConfiguration.java
public final static void main(String[] args) throws Exception { // Use custom message parser / writer to customize the way HTTP // messages are parsed from and written out to the data stream. HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() { @Override/*w w w .jav a2s .co m*/ public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer, MessageConstraints constraints) { LineParser lineParser = new BasicLineParser() { @Override public Header parseHeader(final CharArrayBuffer buffer) { try { return super.parseHeader(buffer); } catch (ParseException ex) { return new BasicHeader(buffer.toString(), null); } } }; return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints) { @Override protected boolean reject(final CharArrayBuffer line, int count) { // try to ignore all garbage preceding a status line infinitely return false; } }; } }; HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory(); // Use a custom connection factory to customize the process of // initialization of outgoing HTTP connections. Beside standard connection // configuration parameters HTTP connection factory can define message // parser / writer routines to be employed by individual connections. HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory( requestWriterFactory, responseParserFactory); // Client HTTP connection objects when fully initialized can be bound to // an arbitrary network socket. The process of network socket initialization, // its connection to a remote address and binding to a local one is controlled // by a connection socket factory. // SSL context for secure connections can be created either based on // system or application specific properties. SSLContext sslcontext = SSLContexts.createSystemDefault(); // Create a registry of custom connection socket factories for supported // protocol schemes. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslcontext)).build(); // Use custom DNS resolver to override the system DNS resolution. DnsResolver dnsResolver = new SystemDefaultDnsResolver() { @Override public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("myhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) }; } else { return super.resolve(host); } } }; // Create a connection manager with custom configuration. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry, connFactory, dnsResolver); // Create socket configuration SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build(); // Configure the connection manager to use socket configuration either // by default or for a specific host. connManager.setDefaultSocketConfig(socketConfig); connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig); // Validate connections after 1 sec of inactivity connManager.setValidateAfterInactivity(1000); // Create message constraints MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200) .setMaxLineLength(2000).build(); // Create connection configuration ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8) .setMessageConstraints(messageConstraints).build(); // Configure the connection manager to use connection configuration either // by default or for a specific host. connManager.setDefaultConnectionConfig(connectionConfig); connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT); // Configure total max or per route limits for persistent connections // that can be kept in the pool or leased by the connection manager. connManager.setMaxTotal(100); connManager.setDefaultMaxPerRoute(10); connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20); // Use custom cookie store if necessary. CookieStore cookieStore = new BasicCookieStore(); // Use custom credentials provider if necessary. CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // Create global request configuration RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) .setExpectContinueEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build(); // Create an HttpClient with the given custom dependencies and configuration. CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager) .setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credentialsProvider) .setProxy(new HttpHost("myproxy", 8080)).setDefaultRequestConfig(defaultRequestConfig).build(); try { HttpGet httpget = new HttpGet("http://httpbin.org/get"); // Request configuration can be overridden at the request level. // They will take precedence over the one set at the client level. RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000) .setConnectTimeout(5000).setConnectionRequestTimeout(5000) .setProxy(new HttpHost("myotherproxy", 8080)).build(); httpget.setConfig(requestConfig); // Execution context can be customized locally. HttpClientContext context = HttpClientContext.create(); // Contextual attributes set the local context level will take // precedence over those set at the client level. context.setCookieStore(cookieStore); context.setCredentialsProvider(credentialsProvider); System.out.println("executing request " + httpget.getURI()); CloseableHttpResponse response = httpclient.execute(httpget, context); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("----------------------------------------"); // Once the request has been executed the local context can // be used to examine updated state and various objects affected // by the request execution. // Last executed request context.getRequest(); // Execution route context.getHttpRoute(); // Target auth state context.getTargetAuthState(); // Proxy auth state context.getTargetAuthState(); // Cookie origin context.getCookieOrigin(); // Cookie spec used context.getCookieSpec(); // User security token context.getUserToken(); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:com.http.QuickStart.java
public static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from w w w . j av a2 s . c o m HttpGet httpGet = new HttpGet("http://localhost:8081/cring/jsp/user/index.jsp"); 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 either fully consume the response content or abort request // execution by calling CloseableHttpResponse#close(). try { System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } finally { response1.close(); } HttpPost httpPost = new HttpPost("http://localhost:8081/cring/jsp/user/userLogin.do?method=login"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", "057185581120")); nvps.add(new BasicNameValuePair("password", "111111")); 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(); } }