• Java的HTTPClient工具类(附代码实现)


    博文简介:       

            由于工作内容频繁对接第三方系统,用到HTTP协议进行数据传输。

            官方地址:Apache HttpComponents – Apache HttpComponents 

            组件版本:org.apache.httpcomponents:httpclient:4.5.2

            已支持集:SSL + 自定义参数 + Header  的配置 +  httpClinet配置代理

            已实现集

                    1. GET 以URL参数编码发送

                    2. POST 以请求体JSON发送

                    3. POST 以表单的形式发送

            工具函数:(示例)

    1. public class HttpUtil {
    2. // GET URL编码指定字符集 ----------
    3. // url : 资源地址定位 ; param : url?后的参数 ; charSet : URL编码使用字符集,例如:UTF-8
    4. public static String get(String url, Map urlParam, Map header, String charSet, boolean ssl) {
    5. CloseableHttpClient httpClient = ssl ? getHttpClient() : HttpClients.createDefault();
    6. HttpGet httpGet = new HttpGet(charSet == null ? addParams2Url(url, urlParam) : addParams2UrlWithCharSet(url, urlParam, charSet));
    7. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000 * 2).setConnectionRequestTimeout(6000 * 2).setSocketTimeout(6000 * 2).build();
    8. httpGet.setConfig(requestConfig);
    9. try {
    10. // send get request : 发送GET请求
    11. httpGet.setHeaders(createHeader(header));
    12. CloseableHttpResponse response = httpClient.execute(httpGet);
    13. int statusCode = response.getStatusLine().getStatusCode();
    14. if (statusCode != 200) return null;
    15. // do something useful with response body : 业务逻辑
    16. HttpEntity entity = response.getEntity();
    17. String res = EntityUtils.toString(entity, "UTF-8");
    18. EntityUtils.consume(entity);
    19. return res;
    20. } catch (Exception e) {
    21. } finally {
    22. try {
    23. httpClient.close();
    24. } catch (IOException e) {
    25. }
    26. }
    27. return null;
    28. }
    29. private static String addParams2Url(String url, Map params) {
    30. return addParams2UrlWithCharSet(url, params, null);
    31. }
    32. private static String addParams2UrlWithCharSet(String url, Map params, String charSet) {
    33. if (params == null || params.isEmpty()) {
    34. return url;
    35. }
    36. StringBuilder sb = new StringBuilder();
    37. try {
    38. for (Map.Entry entry : params.entrySet()) {
    39. sb.append("&").append(entry.getKey()).append("=");
    40. sb.append(charSet == null ? entry.getValue() : URLEncoder.encode(entry.getValue(), charSet));
    41. }
    42. if (!url.contains("?")) {
    43. sb.deleteCharAt(0).insert(0, "?");
    44. }
    45. } catch (Exception e) {
    46. }
    47. return url + sb;
    48. }
    49. // POST 以请求体JSON发送数据--------------------
    50. public static String postJson(String url, Map urlParam, Map header, String data, boolean ssl) {
    51. CloseableHttpClient httpClient = ssl ? getHttpClient() : HttpClients.createDefault();
    52. HttpPost httpPost = new HttpPost(addParams2Url(url, urlParam));
    53. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000 * 2).setConnectionRequestTimeout(6000 * 2).setSocketTimeout(6000 * 2).build();
    54. httpPost.setConfig(requestConfig);
    55. try {
    56. httpPost.setHeaders(createHeader(header));
    57. httpPost.setEntity(new StringEntity(data, ContentType.APPLICATION_JSON));
    58. CloseableHttpResponse response = httpClient.execute(httpPost);
    59. int statusCode = response.getStatusLine().getStatusCode();
    60. if (statusCode != 200) return null;
    61. HttpEntity entity = response.getEntity();
    62. String res = EntityUtils.toString(entity, "UTF-8");
    63. EntityUtils.consume(entity);
    64. response.close();
    65. return res;
    66. } catch (Exception e) {
    67. } finally {
    68. try {
    69. httpClient.close();
    70. } catch (Exception e) {
    71. }
    72. }
    73. return null;
    74. }
    75. // POST 以表单的形式发送数据-----------
    76. public static String postForm(String url, Map urlParam, Map header, Map data, boolean ssl) {
    77. CloseableHttpClient httpClient = ssl ? getHttpClient() : HttpClients.createDefault();
    78. HttpPost httpPost = new HttpPost(addParams2Url(url, urlParam));
    79. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000 * 2).setConnectionRequestTimeout(6000 * 2).setSocketTimeout(6000 * 2).build();
    80. httpPost.setConfig(requestConfig);
    81. try {
    82. // config header content-type is application/x-www-form-urlencoded : 配置HTTP的Header:content-type
    83. header = header != null ? header : new HashMap<>();
    84. ContentType APPLICATION_FORM_URLENCODED_UTF8 = ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8);
    85. header.put("Content-Type", APPLICATION_FORM_URLENCODED_UTF8.toString());
    86. httpPost.setHeaders(createHeader(header));
    87. // add key-value pair to entity : 设置参数到请求体中
    88. List list = new ArrayList<>();
    89. for (Map.Entry entry : data.entrySet()) {
    90. list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    91. }
    92. if (list.size() > 0) {
    93. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
    94. httpPost.setEntity(entity);
    95. }
    96. CloseableHttpResponse response = httpClient.execute(httpPost);
    97. int statusCode = response.getStatusLine().getStatusCode();
    98. if (statusCode != 200) return null;
    99. HttpEntity entity = response.getEntity();
    100. String res = EntityUtils.toString(entity, "UTF-8");
    101. EntityUtils.consume(entity);
    102. response.close();
    103. return res;
    104. } catch (Exception e) {
    105. } finally {
    106. try {
    107. httpClient.close();
    108. } catch (Exception e) {
    109. }
    110. }
    111. return null;
    112. }
    113. // HTTPS client 创建 --------------------
    114. public static CloseableHttpClient getHttpClient() {
    115. X509TrustManager trustManager = new X509TrustManager() {
    116. @Override
    117. public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    118. }
    119. @Override
    120. public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    121. }
    122. @Override
    123. public X509Certificate[] getAcceptedIssuers() {
    124. return null;
    125. }
    126. };
    127. SSLContext context = null;
    128. try {
    129. context = SSLContext.getInstance("SSL");
    130. context.init(null, new TrustManager[]{trustManager}, null);
    131. return HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(context)).build();
    132. } catch (Exception e) {
    133. }
    134. return null;
    135. }
    136. // 批量创建请求头 --------------------
    137. private static Header[] createHeader(Map header) {
    138. if (header == null || header.isEmpty()) return null;
    139. List
      headers = new ArrayList<>();
    140. for (String key : header.keySet()) {
    141. headers.add(new BasicHeader(key, header.get(key)));
    142. }
    143. return headers.toArray(new Header[]{});
    144. }
    145. }

            配置代理(示例):

    1. public class ClientExecuteProxy {
    2. public static void main(String[] args)throws Exception {
    3. CloseableHttpClient httpclient = HttpClients.createDefault();
    4. try {
    5. HttpHost target = new HttpHost("httpbin.org", 443, "https");
    6. HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
    7. RequestConfig config = RequestConfig.custom()
    8. .setProxy(proxy)
    9. .build();
    10. HttpGet request = new HttpGet("/");
    11. request.setConfig(config);
    12. System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);
    13. CloseableHttpResponse response = httpclient.execute(target, request);
    14. try {
    15. System.out.println("----------------------------------------");
    16. System.out.println(response.getStatusLine());
    17. System.out.println(EntityUtils.toString(response.getEntity()));
    18. } finally {
    19. response.close();
    20. }
    21. } finally {
    22. httpclient.close();
    23. }
    24. }
    25. }
    1. public class ClientProxyAuthentication {
    2. public static void main(String[] args) throws Exception {
    3. CredentialsProvider credsProvider = new BasicCredentialsProvider();
    4. credsProvider.setCredentials(
    5. new AuthScope("localhost", 8888),
    6. new UsernamePasswordCredentials("squid", "squid"));
    7. credsProvider.setCredentials(
    8. new AuthScope("httpbin.org", 80),
    9. new UsernamePasswordCredentials("user", "passwd"));
    10. CloseableHttpClient httpclient = HttpClients.custom()
    11. .setDefaultCredentialsProvider(credsProvider).build();
    12. try {
    13. HttpHost target = new HttpHost("httpbin.org", 80, "http");
    14. HttpHost proxy = new HttpHost("localhost", 8888);
    15. RequestConfig config = RequestConfig.custom()
    16. .setProxy(proxy)
    17. .build();
    18. HttpGet httpget = new HttpGet("/basic-auth/user/passwd");
    19. httpget.setConfig(config);
    20. System.out.println("Executing request " + httpget.getRequestLine() + " to " + target + " via " + proxy);
    21. CloseableHttpResponse response = httpclient.execute(target, httpget);
    22. try {
    23. System.out.println("----------------------------------------");
    24. System.out.println(response.getStatusLine());
    25. System.out.println(EntityUtils.toString(response.getEntity()));
    26. } finally {
    27. response.close();
    28. }
    29. } finally {
    30. httpclient.close();
    31. }
    32. }
    33. }

    参考地址

    1. 官网示例:Apache HttpComponents – HttpClient Examples  

    2. 异步处理:Apache HttpComponents – HttpAsyncClient Quick Start  

    变更记录

    2022-11-13 : 初稿发布

    2022-12-26 :简化实现类的封装,扩展 "配置代理" 及 "代理认证

    ** 希望得到你的参与和支持。 如果内容有描述不恰当的地方,请指出。 谢谢!**

  • 相关阅读:
    【牛客刷题日记】— Javascript 通关秘籍
    idea tomcat部署tomcat项目访问404 mvc项目显示artifact is deployed successfully 访问404
    21. Spring Boot 整合 MyBatis
    Qt状态机框架
    王道22数据结构课后习题(第二章2.2.3)
    【Golang入门】Golang第一天心得
    网络—网络通信基础(理论)
    电脑重装系统word从第二页开始有页眉页脚如何设置
    Maven下载源码出现:Cannot download sources Sources not found for org.springframwork...
    【详细介绍下PostgreSQL】
  • 原文地址:https://blog.csdn.net/qq_41107529/article/details/127827954