HttpClientHelper.java 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. package util;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.google.common.collect.Lists;
  4. import org.apache.commons.lang3.StringUtils;
  5. import org.apache.http.Consts;
  6. import org.apache.http.Header;
  7. import org.apache.http.HttpEntity;
  8. import org.apache.http.client.config.RequestConfig;
  9. import org.apache.http.client.entity.UrlEncodedFormEntity;
  10. import org.apache.http.client.methods.CloseableHttpResponse;
  11. import org.apache.http.client.methods.HttpGet;
  12. import org.apache.http.client.methods.HttpPost;
  13. import org.apache.http.entity.ContentType;
  14. import org.apache.http.entity.StringEntity;
  15. import org.apache.http.impl.client.CloseableHttpClient;
  16. import org.apache.http.impl.client.HttpClientBuilder;
  17. import org.apache.http.impl.client.HttpClients;
  18. import org.apache.http.message.BasicNameValuePair;
  19. import org.apache.http.util.EntityUtils;
  20. import java.io.IOException;
  21. import java.util.List;
  22. /**
  23. * HTTP工具类,参数统一用JSONObject对象进行传递
  24. * 需要注意的是,如果参数对顺序有要求,如有签名校验时
  25. * 在构建JSONObject对象时需要指定ordered = true
  26. * 创建为LinkedHashMap
  27. */
  28. @SuppressWarnings("all")
  29. public class HttpClientHelper {
  30. public static String httpGet(String url) {
  31. return httpGet(url, null, null);
  32. }
  33. public static String httpGet(String url, JSONObject params) {
  34. return httpGet(url, params, null);
  35. }
  36. public static String httpGet(String url, JSONObject params, Header header) {
  37. String result = "";
  38. if (StringUtils.isBlank(url)) return result;
  39. if (params != null && !params.isEmpty()) url = convertGetParams(url, params);
  40. HttpGet httpGet = new HttpGet(url);
  41. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  42. httpGet.setConfig(getHttpConfig());
  43. httpGet.setHeader(header);
  44. try {
  45. try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
  46. HttpEntity entity = response.getEntity();
  47. if (entity != null) {
  48. result = EntityUtils.toString(entity, Consts.UTF_8);
  49. }
  50. }
  51. } catch (Exception e) {
  52. e.printStackTrace();
  53. } finally {
  54. // 关闭连接,释放资源
  55. try {
  56. httpClient.close();
  57. } catch (IOException e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. return result;
  62. }
  63. private static String convertGetParams(String url, JSONObject params) {
  64. StringBuffer sb = url.contains("?") ? new StringBuffer(url) : new StringBuffer(url + "?");
  65. params.forEach((k, v) -> sb.append(k).append("=").append(v).append("&"));
  66. return sb.substring(0, sb.length() - 1);
  67. }
  68. public static String httpPost(String url, JSONObject params) {
  69. return httpPost(url, params, null, ContentType.APPLICATION_JSON);
  70. }
  71. public static String httpPost(String url, JSONObject params, Header header) {
  72. return httpPost(url, params, header, ContentType.APPLICATION_JSON);
  73. }
  74. public static String httpPost(String url, JSONObject params, Header header, ContentType contentType) {
  75. String result = "";
  76. if (StringUtils.isBlank(url)) return result;
  77. //创建默认的httpClient实例
  78. CloseableHttpClient httpClient = HttpClients.createDefault();
  79. //创建httpPost
  80. HttpPost httpPost = new HttpPost(url);
  81. httpPost.addHeader(header);
  82. httpPost.setConfig(getHttpConfig());
  83. StringEntity request;
  84. try {
  85. if (ContentType.APPLICATION_FORM_URLENCODED == contentType) {
  86. List<BasicNameValuePair> pairs = Lists.newArrayList();
  87. params.forEach((key, value) -> pairs.add(new BasicNameValuePair(key, String.valueOf(value))));
  88. request = new UrlEncodedFormEntity(pairs, Consts.UTF_8);
  89. } else {
  90. request = new StringEntity(String.valueOf(params), ContentType.APPLICATION_JSON);
  91. }
  92. httpPost.setEntity(request);
  93. try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
  94. HttpEntity entity = response.getEntity();
  95. if (entity != null) {
  96. result = EntityUtils.toString(entity, Consts.UTF_8);
  97. }
  98. }
  99. } catch (Exception e) {
  100. e.printStackTrace();
  101. } finally {
  102. //关闭连接,释放资源
  103. try {
  104. httpClient.close();
  105. } catch (IOException e) {
  106. e.printStackTrace();
  107. }
  108. }
  109. return result;
  110. }
  111. private static RequestConfig getHttpConfig() {
  112. return RequestConfig.custom()
  113. .setConnectTimeout(10000)//一、连接超时:connectionTimeout-->指的是连接一个url的连接等待时间
  114. .setSocketTimeout(10000)// 二、读取数据超时:SocketTimeout-->指的是连接上一个url,获取response的返回等待时间
  115. .setConnectionRequestTimeout(10000)
  116. .build();
  117. }
  118. }