HttpClient用法

HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送Http请求变得容易,而且也方便开发人员测试接口(基于Http协议的),提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。

org.apache.commons.httpclient.HttpClient与org.apache.http.client.HttpClient的区别

Commons的HttpClient项目现在是生命的尽头,不再被开发,  已被Apache HttpComponents项目HttpClient和HttpCore  模组取代,提供更好的性能和更大的灵活性。  

一、简介

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

下载地址: http://hc.apache.org/downloads.cgi

二、特性

1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1

2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

3. 支持HTTPS协议。

4. 通过Http代理建立透明的连接。

5. 利用CONNECT方法通过Http代理建立隧道的https连接。

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。

7. 插件式的自定义认证方案。

8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。

9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。

10. 自动处理Set-Cookie中的Cookie。

11. 插件式的自定义Cookie策略。

12. Request的输出流可以避免流中内容直接缓冲到socket服务器。

13. Response的输入流可以有效的从socket服务器直接读取相应内容。

14. 在http1.0和http1.1中利用KeepAlive保持持久连接。

15. 直接获取服务器发送的response code和 headers。

16. 设置连接超时的能力。

17. 实验性的支持http1.1 response caching。

18. 源代码基于Apache License 可免费获取。

三、使用方法

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建HttpClient对象。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6. 释放连接。无论执行方法是否成功,都必须释放连接

相关jar包


  
  
  1. commons-cli- 1.2.jar
  2. commons-codec- 1.9.jar
  3. commons-logging- 1.2.jar
  4. fluent-hc- 4.5 .1.jar
  5. httpclient- 4.5 .1.jar
  6. httpclient-cache- 4.5 .1.jar
  7. httpclient-win- 4.5 .1.jar
  8. httpcore- 4.4 .3.jar
  9. httpcore-ab- 4.4 .3.jar
  10. httpcore-nio- 4.4 .3.jar
  11. httpmime- 4.5 .1.jar
  12. jna- 4.1 .0.jar
  13. jna-platform- 4.1 .0.jar

最简单post请求, 源自 http://my.oschina.net/xinxingegeya/blog/282683


  
  
  1. package a;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.Properties;
  7. import org.apache.http.HttpEntity;
  8. import org.apache.http.HttpResponse;
  9. import org.apache.http.NameValuePair;
  10. import org.apache.http.client.HttpClient;
  11. import org.apache.http.client.config.RequestConfig;
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;
  13. import org.apache.http.client.methods.HttpPost;
  14. import org.apache.http.impl.client.DefaultHttpClient;
  15. import org.apache.http.message.BasicNameValuePair;
  16. import org.apache.http.util.EntityUtils;
  17. public class First {
  18. public static void main (String[] args) throws Exception{
  19. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  20. formparams.add( new BasicNameValuePair( "account", ""));
  21. formparams.add( new BasicNameValuePair( "password", ""));
  22. HttpEntity reqEntity = new UrlEncodedFormEntity(formparams, "utf-8");
  23. RequestConfig requestConfig = RequestConfig.custom()
  24. .setConnectTimeout( 5000) //一、连接超时:connectionTimeout-->指的是连接一个url的连接等待时间
  25. .setSocketTimeout( 5000) // 二、读取数据超时:SocketTimeout-->指的是连接上一个url,获取response的返回等待时间
  26. .setConnectionRequestTimeout( 5000)
  27. .build();
  28. HttpClient client = new DefaultHttpClient();
  29. HttpPost post = new HttpPost( "http://cnivi.com.cn/login");
  30. post.setEntity(reqEntity);
  31. post.setConfig(requestConfig);
  32. HttpResponse response = client.execute(post);
  33. if (response.getStatusLine().getStatusCode() == 200) {
  34. HttpEntity resEntity = response.getEntity();
  35. String message = EntityUtils.toString(resEntity, "utf-8");
  36. System.out.println(message);
  37. } else {
  38. System.out.println( "请求失败");
  39. }
  40. }
  41. }

四、实例

主文件

  
  
  1. package com.test;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.UnsupportedEncodingException;
  6. import java.security.KeyManagementException;
  7. import java.security.KeyStore;
  8. import java.security.KeyStoreException;
  9. import java.security.NoSuchAlgorithmException;
  10. import java.security.cert.CertificateException;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. import javax.net.ssl.SSLContext;
  14. import org.apache.http.HttpEntity;
  15. import org.apache.http.NameValuePair;
  16. import org.apache.http.ParseException;
  17. import org.apache.http.client.ClientProtocolException;
  18. import org.apache.http.client.entity.UrlEncodedFormEntity;
  19. import org.apache.http.client.methods.CloseableHttpResponse;
  20. import org.apache.http.client.methods.HttpGet;
  21. import org.apache.http.client.methods.HttpPost;
  22. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  23. import org.apache.http.conn.ssl.SSLContexts;
  24. import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
  25. import org.apache.http.entity.ContentType;
  26. import org.apache.http.entity.mime.MultipartEntityBuilder;
  27. import org.apache.http.entity.mime.content.FileBody;
  28. import org.apache.http.entity.mime.content.StringBody;
  29. import org.apache.http.impl.client.CloseableHttpClient;
  30. import org.apache.http.impl.client.HttpClients;
  31. import org.apache.http.message.BasicNameValuePair;
  32. import org.apache.http.util.EntityUtils;
  33. import org.apache.http.client.config.RequestConfig;
  34. import org.junit.Test;
  35. public class HttpClientTest {
  36.    //方法见下........
  37. }
HttpClientUtils工具类

  
  
  1. package com.bobo.code.web.controller.technology.httpcomponents;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpHost;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.NameValuePair;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.client.config.RequestConfig;
  8. import org.apache.http.client.methods.HttpUriRequest;
  9. import org.apache.http.client.methods.RequestBuilder;
  10. import org.apache.http.conn.routing.HttpRoute;
  11. import org.apache.http.impl.client.CloseableHttpClient;
  12. import org.apache.http.impl.client.HttpClientBuilder;
  13. import org.apache.http.impl.client.HttpClients;
  14. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  15. import org.apache.http.message.BasicNameValuePair;
  16. import org.apache.http.util.EntityUtils;
  17. import java.io.IOException;
  18. import java.util.*;
  19. public class HttpClientUtils {
  20. private static PoolingHttpClientConnectionManager connectionManager = null;
  21. private static HttpClientBuilder httpBuilder = null;
  22. private static RequestConfig requestConfig = null;
  23. private static int MAXCONNECTION = 10;
  24. private static int DEFAULTMAXCONNECTION = 5;
  25. private static String IP = "cnivi.com.cn";
  26. private static int PORT = 80;
  27. static {
  28. //设置http的状态参数
  29. requestConfig = RequestConfig.custom()
  30. .setSocketTimeout( 5000)
  31. .setConnectTimeout( 5000)
  32. .setConnectionRequestTimeout( 5000)
  33. .build();
  34. HttpHost target = new HttpHost(IP, PORT);
  35. connectionManager = new PoolingHttpClientConnectionManager();
  36. connectionManager.setMaxTotal(MAXCONNECTION); //客户端总并行链接最大数
  37. connectionManager.setDefaultMaxPerRoute(DEFAULTMAXCONNECTION); //每个主机的最大并行链接数
  38. connectionManager.setMaxPerRoute( new HttpRoute(target), 20);
  39. httpBuilder = HttpClients.custom();
  40. httpBuilder.setConnectionManager(connectionManager);
  41. }
  42. public static CloseableHttpClient getConnection () {
  43. CloseableHttpClient httpClient = httpBuilder.build();
  44. return httpClient;
  45. }
  46. public static HttpUriRequest getRequestMethod (Map<String, String> map, String url, String method) {
  47. List<NameValuePair> params = new ArrayList<NameValuePair>();
  48. Set<Map.Entry<String, String>> entrySet = map.entrySet();
  49. for (Map.Entry<String, String> e : entrySet) {
  50. String name = e.getKey();
  51. String value = e.getValue();
  52. NameValuePair pair = new BasicNameValuePair(name, value);
  53. params.add(pair);
  54. }
  55. HttpUriRequest reqMethod = null;
  56. if ( "post".equals(method)) {
  57. reqMethod = RequestBuilder.post().setUri(url)
  58. .addParameters(params.toArray( new BasicNameValuePair[params.size()]))
  59. .setConfig(requestConfig).build();
  60. } else if ( "get".equals(method)) {
  61. reqMethod = RequestBuilder.get().setUri(url)
  62. .addParameters(params.toArray( new BasicNameValuePair[params.size()]))
  63. .setConfig(requestConfig).build();
  64. }
  65. return reqMethod;
  66. }
  67. public static void main (String args[]) throws IOException {
  68. Map<String, String> map = new HashMap<String, String>();
  69. map.put( "account", "");
  70. map.put( "password", "");
  71. HttpClient client = getConnection();
  72. HttpUriRequest post = getRequestMethod(map, "http://cnivi.com.cn/login", "post");
  73. HttpResponse response = client.execute(post);
  74. if (response.getStatusLine().getStatusCode() == 200) {
  75. HttpEntity entity = response.getEntity();
  76. String message = EntityUtils.toString(entity, "utf-8");
  77. System.out.println(message);
  78. } else {
  79. System.out.println( "请求失败");
  80. }
  81. }
  82. }
get方式

  
  
  1. /**
  2. * 发送 get请求
  3. */
  4. public void get () {
  5. CloseableHttpClient httpclient = HttpClients.createDefault();
  6. try {
  7. // 创建httpget.
  8. HttpGet httpget = new HttpGet( "http://www.baidu.com/");
  9. System.out.println( "executing request " + httpget.getURI());
  10. // 执行get请求.
  11. CloseableHttpResponse response = httpclient.execute(httpget);
  12. try {
  13. // 获取响应实体
  14. HttpEntity entity = response.getEntity();
  15. System.out.println( "--------------------------------------");
  16. // 打印响应状态
  17. System.out.println(response.getStatusLine());
  18. if (entity != null) {
  19. // 打印响应内容长度
  20. System.out.println( "Response content length: " + entity.getContentLength());
  21. // 打印响应内容
  22. System.out.println( "Response content: " + EntityUtils.toString(entity));
  23. }
  24. System.out.println( "------------------------------------");
  25. } finally {
  26. response.close();
  27. }
  28. } catch (ClientProtocolException e) {
  29. e.printStackTrace();
  30. } catch (ParseException e) {
  31. e.printStackTrace();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. } finally {
  35. // 关闭连接,释放资源
  36. try {
  37. httpclient.close();
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }
post方式 

  
  
  1. /**
  2. * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
  3. */
  4. public void post () {
  5. // 创建默认的httpClient实例.
  6. CloseableHttpClient httpclient = HttpClients.createDefault();
  7. // 创建httppost
  8. HttpPost httppost = new HttpPost( "http://localhost:8080/myDemo/Ajax/serivceJ.action");
  9. // 创建参数队列
  10. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  11. formparams.add( new BasicNameValuePair( "type", "house"));
  12. UrlEncodedFormEntity uefEntity;
  13. try {
  14. uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
  15. httppost.setEntity(uefEntity);
  16. System.out.println( "executing request " + httppost.getURI());
  17. CloseableHttpResponse response = httpclient.execute(httppost);
  18. try {
  19. HttpEntity entity = response.getEntity();
  20. if (entity != null) {
  21. System.out.println( "--------------------------------------");
  22. System.out.println( "Response content: " + EntityUtils.toString(entity, "UTF-8"));
  23. System.out.println( "--------------------------------------");
  24. }
  25. } finally {
  26. response.close();
  27. }
  28. } catch (ClientProtocolException e) {
  29. e.printStackTrace();
  30. } catch (UnsupportedEncodingException e1) {
  31. e1.printStackTrace();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. } finally {
  35. // 关闭连接,释放资源
  36. try {
  37. httpclient.close();
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }

post方式乱码补充 

如果有乱码,可以偿试使用 StringEntity 来替换HttpEntity:


  
  
  1. StringEntity content = new StringEntity(soapRequestData.toString(), Charset.forName( "UTF-8")); // 第二个参数,设置后才会对,内容进行编码
  2. content.setContentType( "application/soap+xml; charset=UTF-8");
  3. content.setContentEncoding( "UTF-8");
  4. httppost.setEntity(content);

具体SOAP协议代码如下:


  
  
  1. package com.isoftstone.core.service.impl;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8. import java.nio.charset.Charset;
  9. import java.util.Scanner;
  10. import org.apache.http.HttpEntity;
  11. import org.apache.http.HttpResponse;
  12. import org.apache.http.client.ClientProtocolException;
  13. import org.apache.http.client.HttpClient;
  14. import org.apache.http.client.entity.EntityBuilder;
  15. import org.apache.http.client.methods.HttpPost;
  16. import org.apache.http.entity.ContentType;
  17. import org.apache.http.entity.StringEntity;
  18. import org.apache.http.impl.client.HttpClients;
  19. import org.apache.http.util.EntityUtils;
  20. import org.apache.log4j.Logger;
  21. import org.jdom.Document;
  22. import org.jdom.Element;
  23. import com.isoftstone.core.common.constant.RequestConstants;
  24. import com.isoftstone.core.common.tools.XmlTool;
  25. import com.isoftstone.core.service.intf.ServiceOfStringPara;
  26. /**
  27. *
  28. *
  29. */
  30. public class DeloittePricingSingleCarImpl implements ServiceOfStringPara {
  31. private String serviceUrl = "http://10.30.0.35:7001/ZSInsUW/Auto/PricingService";
  32. private static Logger log = Logger.getLogger(DeloittePricingSingleCarImpl.class.getName());
  33. public String invoke (String sRequest) {
  34. StringBuffer soapRequestData = new StringBuffer();
  35. soapRequestData.append( "<soapenv:Envelope");
  36. soapRequestData.append( " xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" ");
  37. soapRequestData.append( " xmlns:prov=\"http://provider.webservice.zsins.dtt.com/\">");
  38. soapRequestData.append( " <soapenv:Header/> ");
  39. soapRequestData.append( "<soapenv:Body>");
  40. soapRequestData.append( "<prov:executePrvPricing>");
  41. soapRequestData.append( "<arg0>");
  42. soapRequestData.append( "<![CDATA[" + sRequest + "]]>");
  43. soapRequestData.append( "</arg0>");
  44. soapRequestData.append( "</prov:executePrvPricing>");
  45. soapRequestData.append( " </soapenv:Body>");
  46. soapRequestData.append( "</soapenv:Envelope>");
  47. HttpClient httpclient = HttpClients.createDefault();
  48. HttpPost httppost = new HttpPost(serviceUrl);
  49. StringEntity content = new StringEntity(soapRequestData.toString(), Charset.forName( "UTF-8")); // 第二个参数,设置后才会对,内容进行编码
  50. content.setContentType( "application/soap+xml; charset=UTF-8");
  51. content.setContentEncoding( "UTF-8");
  52. httppost.setEntity(content);
  53. //用下面的服务器端以UTF-8接收到的报文会乱码,原因未知
  54. // HttpEntity reqEntity = EntityBuilder.create().setContentType(
  55. // ContentType.TEXT_PLAIN) // .TEXT_PLAIN
  56. // .setText(soapRequestData.toString()).build();
  57. // httppost.setEntity(reqEntity);
  58. // httppost.addHeader("Content-Type",
  59. // "application/soap+xml; charset=utf-8");
  60. HttpResponse response = null;
  61. Document doc = null;
  62. String returnXml = null;
  63. String sentity = null;
  64. try {
  65. response = httpclient.execute(httppost);
  66. HttpEntity resEntity = response.getEntity();
  67. if (resEntity != null) {
  68. sentity = EntityUtils.toString(resEntity, "UTF-8");
  69. doc = XmlTool.getDocument(sentity, RequestConstants.ENCODE);
  70. System.out.println(doc.toString());
  71. Element eRoot = doc.getRootElement();
  72. Element body = eRoot.getChild( "Body", eRoot.getNamespace());
  73. Element resp = (Element) body.getChildren().get( 0);
  74. Element returnele = resp.getChild( "return");
  75. returnXml = returnele.getText().toString();
  76. }
  77. } catch (ClientProtocolException e) {
  78. e.printStackTrace();
  79. } catch (IOException e) {
  80. e.printStackTrace();
  81. } catch (Exception e) {
  82. e.printStackTrace();
  83. } finally {
  84. log.info( "发送给系统的请求报文:\n" + soapRequestData.toString());
  85. log.info( "系统返回的响应报文:\n" + sentity);
  86. log.info( "返回给核心的的报文:\n" + returnXml);
  87. }
  88. return returnXml;
  89. }
  90. public String getServiceUrl () {
  91. return serviceUrl;
  92. }
  93. public void setServiceUrl (String serviceUrl) {
  94. this.serviceUrl = serviceUrl;
  95. }
  96. public static void main (String[] args) throws Exception{
  97. File file = new File( "D:/test.txt");
  98. System.out.println(file.exists());
  99. String temp2 = null;
  100. StringBuilder sb2 = new StringBuilder();
  101. InputStreamReader isr = new InputStreamReader( new FileInputStream(file), "GBK");
  102. BufferedReader br = new BufferedReader(isr);
  103. temp2 = br.readLine();
  104. while( temp2 != null ){
  105. sb2.append(temp2);
  106. temp2 = br.readLine();
  107. }
  108. String sss = sb2.toString();
  109. // System.out.println(sss.toString());
  110. new DeloittePricingSingleCarImpl().invoke(sss);
  111. }
  112. }

 

post提交表单

  
  
  1. /**
  2. * post方式提交表单(模拟用户登录请求)
  3. */
  4. public void postForm () {
  5. // 创建默认的httpClient实例.
  6. CloseableHttpClient httpclient = HttpClients.createDefault();
  7. // 创建httppost
  8. HttpPost httppost = new HttpPost( "http://localhost:8080/myDemo/Ajax/serivceJ.action");
  9. // 创建参数队列
  10. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  11. formparams.add( new BasicNameValuePair( "username", "admin"));
  12. formparams.add( new BasicNameValuePair( "password", "123456"));
  13. UrlEncodedFormEntity uefEntity;
  14. try {
  15. uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
  16. httppost.setEntity(uefEntity);
  17. System.out.println( "executing request " + httppost.getURI());
  18. CloseableHttpResponse response = httpclient.execute(httppost);
  19. try {
  20. HttpEntity entity = response.getEntity();
  21. if (entity != null) {
  22. System.out.println( "--------------------------------------");
  23. System.out.println( "Response content: " + EntityUtils.toString(entity, "UTF-8"));
  24. System.out.println( "--------------------------------------");
  25. }
  26. } finally {
  27. response.close();
  28. }
  29. } catch (ClientProtocolException e) {
  30. e.printStackTrace();
  31. } catch (UnsupportedEncodingException e1) {
  32. e1.printStackTrace();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. } finally {
  36. // 关闭连接,释放资源
  37. try {
  38. httpclient.close();
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. }
文件上传

  
  
  1. /**
  2. * 上传文件
  3. */
  4. public void upload () {
  5. CloseableHttpClient httpclient = HttpClients.createDefault();
  6. try {
  7. HttpPost httppost = new HttpPost( "http://localhost:8080/myDemo/Ajax/serivceFile.action");
  8. FileBody bin = new FileBody( new File( "F:\\image\\sendpix0.jpg"));
  9. StringBody comment = new StringBody( "A binary file of some kind", ContentType.TEXT_PLAIN);
  10. HttpEntity reqEntity = MultipartEntityBuilder.create().addPart( "bin", bin).addPart( "comment", comment).build();
  11. httppost.setEntity(reqEntity);
  12. System.out.println( "executing request " + httppost.getRequestLine());
  13. CloseableHttpResponse response = httpclient.execute(httppost);
  14. try {
  15. System.out.println( "----------------------------------------");
  16. System.out.println(response.getStatusLine());
  17. HttpEntity resEntity = response.getEntity();
  18. if (resEntity != null) {
  19. System.out.println( "Response content length: " + resEntity.getContentLength());
  20. }
  21. EntityUtils.consume(resEntity);
  22. } finally {
  23. response.close();
  24. }
  25. } catch (ClientProtocolException e) {
  26. e.printStackTrace();
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. } finally {
  30. try {
  31. httpclient.close();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. }
ssl连接

  
  
  1. /**
  2. * HttpClient连接SSL
  3. */
  4. public void ssl () {
  5. CloseableHttpClient httpclient = null;
  6. try {
  7. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  8. FileInputStream instream = new FileInputStream( new File( "d:\\tomcat.keystore"));
  9. try {
  10. // 加载keyStore d:\\tomcat.keystore
  11. trustStore.load(instream, "123456".toCharArray());
  12. } catch (CertificateException e) {
  13. e.printStackTrace();
  14. } finally {
  15. try {
  16. instream.close();
  17. } catch (Exception ignore) {
  18. }
  19. }
  20. // 相信自己的CA和所有自签名的证书
  21. SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
  22. // 只允许使用TLSv1协议
  23. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
  24. SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
  25. httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
  26. // 创建http请求(get方式)
  27. HttpGet httpget = new HttpGet( "https://localhost:8443/myDemo/Ajax/serivceJ.action");
  28. System.out.println( "executing request" + httpget.getRequestLine());
  29. CloseableHttpResponse response = httpclient.execute(httpget);
  30. try {
  31. HttpEntity entity = response.getEntity();
  32. System.out.println( "----------------------------------------");
  33. System.out.println(response.getStatusLine());
  34. if (entity != null) {
  35. System.out.println( "Response content length: " + entity.getContentLength());
  36. System.out.println(EntityUtils.toString(entity));
  37. EntityUtils.consume(entity);
  38. }
  39. } finally {
  40. response.close();
  41. }
  42. } catch (ParseException e) {
  43. e.printStackTrace();
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. } catch (KeyManagementException e) {
  47. e.printStackTrace();
  48. } catch (NoSuchAlgorithmException e) {
  49. e.printStackTrace();
  50. } catch (KeyStoreException e) {
  51. e.printStackTrace();
  52. } finally {
  53. if (httpclient != null) {
  54. try {
  55. httpclient.close();
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. }
  59. }
  60. }
  61. }
关于RequestConfig的配置:  

源自:  

http://segmentfault.com/a/1190000000587944

http://blog.csdn.net/walkerjong/article/details/51710945


  
  
  1. public void requestConfig (){
  2. // 新建一个RequestConfig:
  3. RequestConfig defaultRequestConfig = RequestConfig.custom()
  4. //一、连接目标服务器超时时间:ConnectionTimeout-->指的是连接一个url的连接等待时间
  5. .setConnectTimeout( 5000)
  6. //二、读取目标服务器数据超时时间:SocketTimeout-->指的是连接上一个url,获取response的返回等待时间
  7. .setSocketTimeout( 5000)
  8. //三、从连接池获取连接的超时时间:ConnectionRequestTimeout
  9. .setConnectionRequestTimeout( 5000)
  10. .build();
  11. // 这个超时可以设置为客户端级别,作为所有请求的默认值:
  12. CloseableHttpClient httpclient = HttpClients.custom()
  13. .setDefaultRequestConfig(defaultRequestConfig)
  14. .build();
  15. // httpclient.execute(httppost);的时候可以让httppost直接享受到httpclient中的默认配置.
  16. // Request不会继承客户端级别的请求配置,所以在自定义Request的时候,需要将客户端的默认配置拷贝过去:
  17. HttpGet httpget = new HttpGet( "http://www.apache.org/");
  18. RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
  19. .setProxy( new HttpHost( "myotherproxy", 8080))
  20. .build();
  21. httpget.setConfig(requestConfig);
  22. // httpget可以单独地使用新copy的requestConfig请求配置,不会对别的request请求产生影响
  23. }

httpGet或httpPost 的abort()和releaseConnection()差异


  
  
  1. //httpPost.abort();//中断请求,接下来可以开始另一段请求,所以个人理应,用这个应该可以在session中虚拟登录
  2. //httpPost.releaseConnection();//释放请求.如果释放了相当于要清空session

可知模拟登录可以如下:  源自 http://bbs.csdn.net/topics/390195343


  
  
  1. package com.bms.core;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import org.apache.http.Consts;
  6. import org.apache.http.HttpEntity;
  7. import org.apache.http.HttpResponse;
  8. import org.apache.http.NameValuePair;
  9. import org.apache.http.client.ClientProtocolException;
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;
  11. import org.apache.http.client.methods.HttpGet;
  12. import org.apache.http.client.methods.HttpPost;
  13. import org.apache.http.impl.client.DefaultHttpClient;
  14. import org.apache.http.message.BasicNameValuePair;
  15. import org.apache.http.util.EntityUtils;
  16. import com.bms.util.CommonUtil;
  17. public class Test2 {
  18. /**
  19. * @param args
  20. * @throws IOException
  21. * @throws ClientProtocolException
  22. */
  23. public static void main (String[] args) throws ClientProtocolException, IOException {
  24. DefaultHttpClient httpclient = new DefaultHttpClient();
  25. HttpGet httpGet = new HttpGet( "http://www.baidu.com");
  26. String body = "";
  27. HttpResponse response;
  28. HttpEntity entity;
  29. response = httpclient.execute(httpGet);
  30. entity = response.getEntity();
  31. body = EntityUtils.toString(entity); //这个就是页面源码了
  32. httpGet.abort(); //中断请求,接下来可以开始另一段请求
  33. System.out.println(body);
  34. //httpGet.releaseConnection();//释放请求.如果释放了相当于要清空session
  35. //以下是post方法
  36. HttpPost httpPost = new HttpPost( "http://www.baidu.com"); //一定要改成可以提交的地址,这里用百度代替
  37. List <NameValuePair> nvps = new ArrayList <NameValuePair>();
  38. nvps.add( new BasicNameValuePair( "name", "1")); //名值对
  39. nvps.add( new BasicNameValuePair( "account", "xxxx"));
  40. httpPost.setEntity( new UrlEncodedFormEntity(nvps, Consts.UTF_8));
  41. response = httpclient.execute(httpPost);
  42. entity = response.getEntity();
  43. body = EntityUtils.toString(entity);
  44. System.out.println( "Login form get: " + response.getStatusLine()); //这个可以打印状态
  45. httpPost.abort();
  46. System.out.println(body);
  47. httpPost.releaseConnection();
  48. }
  49. }

源自  http://blog.csdn.net/wangpeng047/article/details/19624529#reply

其它相关资料: 非CloseableHttpClient  HTTPClient模块的HttpGet和HttpPost

HttpClient 4.3教程

httpclient异常情况分析

我项目中用到的HttpClientUtil (2016/12/17)


  
  
  1. package com.isoftstone.pcis.isc.util;
  2. import java.io.IOException;
  3. import java.io.InterruptedIOException;
  4. import java.net.UnknownHostException;
  5. import javax.net.ssl.SSLException;
  6. import javax.net.ssl.SSLHandshakeException;
  7. import org.apache.http.HttpEntityEnclosingRequest;
  8. import org.apache.http.HttpRequest;
  9. import org.apache.http.NoHttpResponseException;
  10. import org.apache.http.client.HttpRequestRetryHandler;
  11. import org.apache.http.client.protocol.HttpClientContext;
  12. import org.apache.http.config.Registry;
  13. import org.apache.http.config.RegistryBuilder;
  14. import org.apache.http.conn.ConnectTimeoutException;
  15. import org.apache.http.conn.socket.ConnectionSocketFactory;
  16. import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
  17. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  18. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  19. import org.apache.http.impl.client.CloseableHttpClient;
  20. import org.apache.http.impl.client.HttpClients;
  21. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  22. import org.apache.http.protocol.HttpContext;
  23. import com.isoftstone.pcis.isc.util.ProperUtil;
  24. public class HttpClientUtil {
  25. private static CloseableHttpClient httpclient = null;
  26. static final int maxTotal=Integer.valueOf(ProperUtil.get( "maxTotal")).intValue(); //总最大连接数
  27. static final int defaultMaxPerRoute=Integer.valueOf(ProperUtil.get( "corePoolSize")).intValue(); //每条线路最大连接数 = 本系统核心线程数 , 这样永远不会超过最大连接
  28. public static CloseableHttpClient getHttpClient () {
  29. if ( null == httpclient) {
  30. synchronized (HttpClientUtil.class) {
  31. if ( null == httpclient) {
  32. httpclient = getNewHttpClient();
  33. }
  34. }
  35. }
  36. return httpclient;
  37. }
  38. private static CloseableHttpClient getNewHttpClient () {
  39. // 设置连接池
  40. ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
  41. LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
  42. Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register( "http", plainsf).register( "https", sslsf).build();
  43. PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
  44. // 配置最大连接数
  45. cm.setMaxTotal(maxTotal);
  46. // 配置每条线路的最大连接数
  47. cm.setDefaultMaxPerRoute(defaultMaxPerRoute);
  48. // 请求重试处理
  49. HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
  50. @Override
  51. public boolean retryRequest (IOException exception,
  52. int executionCount, HttpContext context) {
  53. if (executionCount >= 2) { // 如果已经重试了2次,就放弃
  54. return false;
  55. }
  56. if (exception instanceof NoHttpResponseException) { // 如果服务器丢掉了连接,那么就重试
  57. return true;
  58. }
  59. if (exception instanceof SSLHandshakeException) { // 不要重试SSL握手异常
  60. return false;
  61. }
  62. if (exception instanceof InterruptedIOException) { // 超时
  63. return false;
  64. }
  65. if (exception instanceof UnknownHostException) { // 目标服务器不可达
  66. return false;
  67. }
  68. if (exception instanceof ConnectTimeoutException) { // 连接被拒绝
  69. return false;
  70. }
  71. if (exception instanceof SSLException) { // SSL握手异常
  72. return false;
  73. }
  74. HttpClientContext clientContext = HttpClientContext.adapt(context);
  75. HttpRequest request = clientContext.getRequest();
  76. if (!(request instanceof HttpEntityEnclosingRequest)) {
  77. return true;
  78. }
  79. return false;
  80. }
  81. };
  82. CloseableHttpClient newHttpclient= null;
  83. newHttpclient = HttpClients.custom()
  84. .setConnectionManager(cm)
  85. // .setDefaultRequestConfig(requestConfig)
  86. .setRetryHandler(httpRequestRetryHandler)
  87. .build();
  88. return newHttpclient;
  89. }
  90. }

我自己整理的HttpClientTool


  
  
  1. package com.isoftstone.core.util;
  2. import java.io.IOException;
  3. import java.io.InterruptedIOException;
  4. import java.net.UnknownHostException;
  5. import javax.net.ssl.SSLException;
  6. import javax.net.ssl.SSLHandshakeException;
  7. import org.apache.http.HttpEntityEnclosingRequest;
  8. import org.apache.http.HttpHost;
  9. import org.apache.http.HttpRequest;
  10. import org.apache.http.NoHttpResponseException;
  11. import org.apache.http.client.HttpRequestRetryHandler;
  12. import org.apache.http.client.config.RequestConfig;
  13. import org.apache.http.client.protocol.HttpClientContext;
  14. import org.apache.http.config.Registry;
  15. import org.apache.http.config.RegistryBuilder;
  16. import org.apache.http.conn.ConnectTimeoutException;
  17. import org.apache.http.conn.routing.HttpRoute;
  18. import org.apache.http.conn.socket.ConnectionSocketFactory;
  19. import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
  20. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  21. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  22. import org.apache.http.impl.client.CloseableHttpClient;
  23. import org.apache.http.impl.client.HttpClients;
  24. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  25. import org.apache.http.protocol.HttpContext;
  26. /**
  27. * org.apache.http.impl.client.CloseableHttpClient链接池生成工具
  28. * @reference http://www.cnblogs.com/whatlonelytear/articles/4835538.html
  29. * @author King
  30. * @date 20170601
  31. */
  32. public class HttpClientTool {
  33. // org.apache.http.impl.client.CloseableHttpClient
  34. private static CloseableHttpClient httpclient = null;
  35. // 这里就直接默认固定了,因为以下三个参数在新建的method中仍然可以重新配置并被覆盖.
  36. static final int connectionRequestTimeout = 5000; // ms毫秒,从池中获取链接超时时间
  37. static final int connectTimeout = 5000; // ms毫秒,建立链接超时时间
  38. static final int socketTimeout = 30000; // ms毫秒,读取超时时间
  39. // 总配置,主要涉及是以下两个参数,如果要作调整没有用到properties会比较后麻烦,但鉴于一经粘贴,随处可用的特点,就不再做依赖性配置化处理了.
  40. // 而且这个参数同一家公司基本不会变动.
  41. static final int maxTotal = 500; // 最大总并发,很重要的参数
  42. static final int maxPerRoute = 100; // 每路并发,很重要的参数
  43. // 正常情况这里应该配成MAP或LIST
  44. // 细化配置参数,用来对每路参数做精细化处理,可以管控各ip的流量,比如默认配置请求baidu:80端口最大100个并发链接,
  45. static final String detailHostName = "http://www.baidu.com"; // 每个细化配置之ip(不重要,在特殊场景很有用)
  46. static final int detailPort = 80; // 每个细化配置之port(不重要,在特殊场景很有用)
  47. static final int detailMaxPerRoute = 100; // 每个细化配置之最大并发数(不重要,在特殊场景很有用)
  48. public static CloseableHttpClient getHttpClient () {
  49. if ( null == httpclient) {
  50. synchronized (HttpClientTool.class) {
  51. if ( null == httpclient) {
  52. httpclient = init();
  53. }
  54. }
  55. }
  56. return httpclient;
  57. }
  58. /**
  59. * 链接池初始化 这里最重要的一点理解就是. 让CloseableHttpClient 一直活在池的世界里, 但是HttpPost却一直用完就消掉.
  60. * 这样可以让链接一直保持着.
  61. *
  62. * @return
  63. */
  64. private static CloseableHttpClient init () {
  65. CloseableHttpClient newHttpclient = null;
  66. // 设置连接池
  67. ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
  68. LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
  69. Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register( "http", plainsf).register( "https", sslsf).build();
  70. PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
  71. // 将最大连接数增加
  72. cm.setMaxTotal(maxTotal);
  73. // 将每个路由基础的连接增加
  74. cm.setDefaultMaxPerRoute(maxPerRoute);
  75. // 细化配置开始,其实这里用Map或List的for循环来配置每个链接,在特殊场景很有用.
  76. // 将每个路由基础的连接做特殊化配置,一般用不着
  77. HttpHost httpHost = new HttpHost(detailHostName, detailPort);
  78. // 将目标主机的最大连接数增加
  79. cm.setMaxPerRoute( new HttpRoute(httpHost), detailMaxPerRoute);
  80. // cm.setMaxPerRoute(new HttpRoute(httpHost2),
  81. // detailMaxPerRoute2);//可以有细化配置2
  82. // cm.setMaxPerRoute(new HttpRoute(httpHost3),
  83. // detailMaxPerRoute3);//可以有细化配置3
  84. // 细化配置结束
  85. // 请求重试处理
  86. HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
  87. @Override
  88. public boolean retryRequest (IOException exception, int executionCount, HttpContext context) {
  89. if (executionCount >= 2) { // 如果已经重试了2次,就放弃
  90. return false;
  91. }
  92. if (exception instanceof NoHttpResponseException) { // 如果服务器丢掉了连接,那么就重试
  93. return true;
  94. }
  95. if (exception instanceof SSLHandshakeException) { // 不要重试SSL握手异常
  96. return false;
  97. }
  98. if (exception instanceof InterruptedIOException) { // 超时
  99. return false;
  100. }
  101. if (exception instanceof UnknownHostException) { // 目标服务器不可达
  102. return false;
  103. }
  104. if (exception instanceof ConnectTimeoutException) { // 连接被拒绝
  105. return false;
  106. }
  107. if (exception instanceof SSLException) { // SSL握手异常
  108. return false;
  109. }
  110. HttpClientContext clientContext = HttpClientContext.adapt(context);
  111. HttpRequest request = clientContext.getRequest();
  112. // 如果请求是幂等的,就再次尝试
  113. if (!(request instanceof HttpEntityEnclosingRequest)) {
  114. return true;
  115. }
  116. return false;
  117. }
  118. };
  119. // 配置请求的超时设置
  120. RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
  121. newHttpclient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).setRetryHandler(httpRequestRetryHandler).build();
  122. return newHttpclient;
  123. }
  124. }

  
  
  1. package com.alqsoft.utils;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.net.URI;
  6. import java.net.URISyntaxException;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import org.apache.commons.logging.Log;
  10. import org.apache.commons.logging.LogFactory;
  11. import org.apache.http.HttpEntity;
  12. import org.apache.http.HttpResponse;
  13. import org.apache.http.NameValuePair;
  14. import org.apache.http.ParseException;
  15. import org.apache.http.client.ClientProtocolException;
  16. import org.apache.http.client.config.CookieSpecs;
  17. import org.apache.http.client.config.RequestConfig;
  18. import org.apache.http.client.entity.UrlEncodedFormEntity;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值