HttpClient 发送 HTTP、HTTPS 请求的简单封装

from: HttpClient 发送 HTTP、HTTPS 请求的简单封装
See Also:轻松把玩HttpClient

最近这几周,一直在忙同一个项目,刚开始是了解需求,需求有一定了解之后,就开始调第三方的接口。由于第三方给提供的文档很模糊,在调接口的时候,出了很多问题,一直在沟通协调,具体的无奈就不说了,由于接口的访问协议是通过 HTTP 和 HTTPS 通讯的,因此封装了一个简单的请求工具类,由于时间紧迫,并没有额外的时间对工具类进行优化和扩展,如果后续空出时间的话,我会对该工具类继续进行优化和扩展的。

引用

首先说一下该类中需要引入的 jar 包,apache 的 httpclient 包,版本号为 4.5,如有需要的话,可以引一下。

代码

  1. <span style=“font-family:Comic Sans MS;”>import org.apache.commons.io.IOUtils;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.HttpStatus;
  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.entity.UrlEncodedFormEntity;
  9. import org.apache.http.client.methods.CloseableHttpResponse;
  10. import org.apache.http.client.methods.HttpGet;
  11. import org.apache.http.client.methods.HttpPost;
  12. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  13. import org.apache.http.conn.ssl.SSLContextBuilder;
  14. import org.apache.http.conn.ssl.TrustStrategy;
  15. import org.apache.http.conn.ssl.X509HostnameVerifier;
  16. import org.apache.http.entity.StringEntity;
  17. import org.apache.http.impl.client.CloseableHttpClient;
  18. import org.apache.http.impl.client.DefaultHttpClient;
  19. import org.apache.http.impl.client.HttpClients;
  20. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  21. import org.apache.http.message.BasicNameValuePair;
  22. import org.apache.http.util.EntityUtils;
  23. import javax.net.ssl.SSLContext;
  24. import javax.net.ssl.SSLException;
  25. import javax.net.ssl.SSLSession;
  26. import javax.net.ssl.SSLSocket;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.nio.charset.Charset;
  30. import java.security.GeneralSecurityException;
  31. import java.security.cert.CertificateException;
  32. import java.security.cert.X509Certificate;
  33. import java.util.ArrayList;
  34. import java.util.HashMap;
  35. import java.util.List;
  36. import java.util.Map;
  37. /**
  38.  * HTTP 请求工具类
  39.  *
  40.  * @author : liii
  41.  * @version : 1.0.0
  42.  * @date : 2015/7/21
  43.  * @see : TODO
  44.  */
  45. public class HttpUtil {
  46.     private static PoolingHttpClientConnectionManager connMgr;
  47.     private static RequestConfig requestConfig;
  48.     private static final int MAX_TIMEOUT = 7000;
  49.     static {
  50.         // 设置连接池
  51.         connMgr = new PoolingHttpClientConnectionManager();
  52.         // 设置连接池大小
  53.         connMgr.setMaxTotal(100);
  54.         connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
  55.         RequestConfig.Builder configBuilder = RequestConfig.custom();
  56.         // 设置连接超时
  57.         configBuilder.setConnectTimeout(MAX_TIMEOUT);
  58.         // 设置读取超时
  59.         configBuilder.setSocketTimeout(MAX_TIMEOUT);
  60.         // 设置从连接池获取连接实例的超时
  61.         configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
  62.         // 在提交请求之前 测试连接是否可用
  63.         configBuilder.setStaleConnectionCheckEnabled(true);
  64.         requestConfig = configBuilder.build();
  65.     }
  66.     /**
  67.      * 发送 GET 请求(HTTP),不带输入数据
  68.      * @param url
  69.      * @return
  70.      */
  71.     public static String doGet(String url) {
  72.         return doGet(url, new HashMap<String, Object>());
  73.     }
  74.     /**
  75.      * 发送 GET 请求(HTTP),K-V形式
  76.      * @param url
  77.      * @param params
  78.      * @return
  79.      */
  80.     public static String doGet(String url, Map<String, Object> params) {
  81.         String apiUrl = url;
  82.         StringBuffer param = new StringBuffer();
  83.         int i = 0;
  84.         for (String key : params.keySet()) {
  85.             if (i == 0)
  86.                 param.append(“?”);
  87.             else
  88.                 param.append(“&”);
  89.             param.append(key).append(“=”).append(params.get(key));
  90.             i++;
  91.         }
  92.         apiUrl += param;
  93.         String result = null;
  94.         HttpClient httpclient = new DefaultHttpClient();
  95.         try {
  96.             HttpGet httpPost = new HttpGet(apiUrl);
  97.             HttpResponse response = httpclient.execute(httpPost);
  98.             int statusCode = response.getStatusLine().getStatusCode();
  99.             System.out.println(“执行状态码 : “ + statusCode);
  100.             HttpEntity entity = response.getEntity();
  101.             if (entity != null) {
  102.                 InputStream instream = entity.getContent();
  103.                 result = IOUtils.toString(instream, “UTF-8”);
  104.             }
  105.         } catch (IOException e) {
  106.             e.printStackTrace();
  107.         }
  108.         return result;
  109.     }
  110.     /**
  111.      * 发送 POST 请求(HTTP),不带输入数据
  112.      * @param apiUrl
  113.      * @return
  114.      */
  115.     public static String doPost(String apiUrl) {
  116.         return doPost(apiUrl, new HashMap<String, Object>());
  117.     }
  118.     /**
  119.      * 发送 POST 请求(HTTP),K-V形式
  120.      * @param apiUrl API接口URL
  121.      * @param params 参数map
  122.      * @return
  123.      */
  124.     public static String doPost(String apiUrl, Map<String, Object> params) {
  125.         CloseableHttpClient httpClient = HttpClients.createDefault();
  126.         String httpStr = null;
  127.         HttpPost httpPost = new HttpPost(apiUrl);
  128.         CloseableHttpResponse response = null;
  129.         try {
  130.             httpPost.setConfig(requestConfig);
  131.             List<NameValuePair> pairList = new ArrayList<>(params.size());
  132.             for (Map.Entry<String, Object> entry : params.entrySet()) {
  133.                 NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
  134.                         .getValue().toString());
  135.                 pairList.add(pair);
  136.             }
  137.             httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName(“UTF-8”)));
  138.             response = httpClient.execute(httpPost);
  139.             System.out.println(response.toString());
  140.             HttpEntity entity = response.getEntity();
  141.             httpStr = EntityUtils.toString(entity, “UTF-8”);
  142.         } catch (IOException e) {
  143.             e.printStackTrace();
  144.         } finally {
  145.             if (response != null) {
  146.                 try {
  147.                     EntityUtils.consume(response.getEntity());
  148.                 } catch (IOException e) {
  149.                     e.printStackTrace();
  150.                 }
  151.             }
  152.         }
  153.         return httpStr;
  154.     }
  155.     /**
  156.      * 发送 POST 请求(HTTP),JSON形式
  157.      * @param apiUrl
  158.      * @param json json对象
  159.      * @return
  160.      */
  161.     public static String doPost(String apiUrl, Object json) {
  162.         CloseableHttpClient httpClient = HttpClients.createDefault();
  163.         String httpStr = null;
  164.         HttpPost httpPost = new HttpPost(apiUrl);
  165.         CloseableHttpResponse response = null;
  166.         try {
  167.             httpPost.setConfig(requestConfig);
  168.             StringEntity stringEntity = new StringEntity(json.toString(),“UTF-8”);//解决中文乱码问题
  169.             stringEntity.setContentEncoding(“UTF-8”);
  170.             stringEntity.setContentType(“application/json”);
  171.             httpPost.setEntity(stringEntity);
  172.             response = httpClient.execute(httpPost);
  173.             HttpEntity entity = response.getEntity();
  174.             System.out.println(response.getStatusLine().getStatusCode());
  175.             httpStr = EntityUtils.toString(entity, “UTF-8”);
  176.         } catch (IOException e) {
  177.             e.printStackTrace();
  178.         } finally {
  179.             if (response != null) {
  180.                 try {
  181.                     EntityUtils.consume(response.getEntity());
  182.                 } catch (IOException e) {
  183.                     e.printStackTrace();
  184.                 }
  185.             }
  186.         }
  187.         return httpStr;
  188.     }
  189.     /**
  190.      * 发送 SSL POST 请求(HTTPS),K-V形式
  191.      * @param apiUrl API接口URL
  192.      * @param params 参数map
  193.      * @return
  194.      */
  195.     public static String doPostSSL(String apiUrl, Map<String, Object> params) {
  196.         CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
  197.         HttpPost httpPost = new HttpPost(apiUrl);
  198.         CloseableHttpResponse response = null;
  199.         String httpStr = null;
  200.         try {
  201.             httpPost.setConfig(requestConfig);
  202.             List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
  203.             for (Map.Entry<String, Object> entry : params.entrySet()) {
  204.                 NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
  205.                         .getValue().toString());
  206.                 pairList.add(pair);
  207.             }
  208.             httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName(“utf-8”)));
  209.             response = httpClient.execute(httpPost);
  210.             int statusCode = response.getStatusLine().getStatusCode();
  211.             if (statusCode != HttpStatus.SC_OK) {
  212.                 return null;
  213.             }
  214.             HttpEntity entity = response.getEntity();
  215.             if (entity == null) {
  216.                 return null;
  217.             }
  218.             httpStr = EntityUtils.toString(entity, “utf-8”);
  219.         } catch (Exception e) {
  220.             e.printStackTrace();
  221.         } finally {
  222.             if (response != null) {
  223.                 try {
  224.                     EntityUtils.consume(response.getEntity());
  225.                 } catch (IOException e) {
  226.                     e.printStackTrace();
  227.                 }
  228.             }
  229.         }
  230.         return httpStr;
  231.     }
  232.     /**
  233.      * 发送 SSL POST 请求(HTTPS),JSON形式
  234.      * @param apiUrl API接口URL
  235.      * @param json JSON对象
  236.      * @return
  237.      */
  238.     public static String doPostSSL(String apiUrl, Object json) {
  239.         CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
  240.         HttpPost httpPost = new HttpPost(apiUrl);
  241.         CloseableHttpResponse response = null;
  242.         String httpStr = null;
  243.         try {
  244.             httpPost.setConfig(requestConfig);
  245.             StringEntity stringEntity = new StringEntity(json.toString(),“UTF-8”);//解决中文乱码问题
  246.             stringEntity.setContentEncoding(“UTF-8”);
  247.             stringEntity.setContentType(“application/json”);
  248.             httpPost.setEntity(stringEntity);
  249.             response = httpClient.execute(httpPost);
  250.             int statusCode = response.getStatusLine().getStatusCode();
  251.             if (statusCode != HttpStatus.SC_OK) {
  252.                 return null;
  253.             }
  254.             HttpEntity entity = response.getEntity();
  255.             if (entity == null) {
  256.                 return null;
  257.             }
  258.             httpStr = EntityUtils.toString(entity, “utf-8”);
  259.         } catch (Exception e) {
  260.             e.printStackTrace();
  261.         } finally {
  262.             if (response != null) {
  263.                 try {
  264.                     EntityUtils.consume(response.getEntity());
  265.                 } catch (IOException e) {
  266.                     e.printStackTrace();
  267.                 }
  268.             }
  269.         }
  270.         return httpStr;
  271.     }
  272.     /**
  273.      * 创建SSL安全连接
  274.      *
  275.      * @return
  276.      */
  277.     private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
  278.         SSLConnectionSocketFactory sslsf = null;
  279.         try {
  280.             SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(nullnew TrustStrategy() {
  281.                 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  282.                     return true;
  283.                 }
  284.             }).build();
  285.             sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
  286.                 @Override
  287.                 public boolean verify(String arg0, SSLSession arg1) {
  288.                     return true;
  289.                 }
  290.                 @Override
  291.                 public void verify(String host, SSLSocket ssl) throws IOException {
  292.                 }
  293.                 @Override
  294.                 public void verify(String host, X509Certificate cert) throws SSLException {
  295.                 }
  296.                 @Override
  297.                 public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
  298.                 }
  299.             });
  300.         } catch (GeneralSecurityException e) {
  301.             e.printStackTrace();
  302.         }
  303.         return sslsf;
  304.     }
  305.     /**
  306.      * 测试方法
  307.      * @param args
  308.      */
  309.     public static void main(String[] args) throws Exception {
  310.     }
  311. }</span>

结束语

工具类封装的比较粗糙,后续还会继续优化的,如果小伙伴们有更好的选择的话,希望也能够分享出来,大家一起学习。
此条目发表在java分类目录,贴了标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注