HttpClientUtil.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. package com.fuint.common.util;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.NameValuePair;
  5. import org.apache.http.client.ClientProtocolException;
  6. import org.apache.http.client.ResponseHandler;
  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.entity.StringEntity;
  13. import org.apache.http.impl.client.CloseableHttpClient;
  14. import org.apache.http.impl.client.HttpClients;
  15. import org.apache.http.message.BasicNameValuePair;
  16. import org.apache.http.util.EntityUtils;
  17. import java.io.IOException;
  18. import java.io.UnsupportedEncodingException;
  19. import java.util.*;
  20. /**
  21. * 基于 apache httpClient4.5的HTTP工具类
  22. *
  23. * Created by FSQ
  24. * CopyRight https://www.fuint.cn
  25. */
  26. public class HttpClientUtil {
  27. public static String doGet(String url) {
  28. return doGet(url, null);
  29. }
  30. public static String doGet(String url, Map<String, String> headers) {
  31. CloseableHttpClient httpClient = null;
  32. CloseableHttpResponse response = null;
  33. String result = "";
  34. try {
  35. // 通过址默认配置创建一个httpClient实例
  36. httpClient = HttpClients.createDefault();
  37. // 创建httpGet远程连接实例
  38. HttpGet httpGet = new HttpGet(url);
  39. if (headers != null && headers.size() > 0) {
  40. for(Map.Entry<String, String> entry : headers.entrySet()){
  41. httpGet.addHeader(entry.getKey(), entry.getValue());
  42. }
  43. }
  44. // 设置配置请求参数
  45. // 连接主机服务超时时间、请求超时时间、数据读取超时时间
  46. RequestConfig requestConfig = RequestConfig.custom()
  47. .setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(10000)
  48. .build();
  49. // 为httpGet实例设置配置
  50. httpGet.setConfig(requestConfig);
  51. // 执行get请求得到返回对象
  52. response = httpClient.execute(httpGet);
  53. // 通过返回对象获取返回数据
  54. HttpEntity entity = response.getEntity();
  55. // 通过EntityUtils中的toString方法将结果转换为字符串
  56. result = org.apache.http.util.EntityUtils.toString(entity);
  57. } catch (ClientProtocolException e) {
  58. e.printStackTrace();
  59. } catch (IOException e) {
  60. e.printStackTrace();
  61. } finally {
  62. // 关闭资源
  63. if (null != response) {
  64. try {
  65. response.close();
  66. } catch (IOException e) {
  67. e.printStackTrace();
  68. }
  69. }
  70. if (null != httpClient) {
  71. try {
  72. httpClient.close();
  73. } catch (IOException e) {
  74. e.printStackTrace();
  75. }
  76. }
  77. }
  78. return result;
  79. }
  80. public static String doPost(String url, Map<String, Object> paramMap) {
  81. return doPost(url, paramMap, null);
  82. }
  83. public static String doPost(String url, Map<String, Object> paramMap, Map<String, String> headers) {
  84. return doPost(url, paramMap, headers, "application/x-www-form-urlencoded", "UTF-8");
  85. }
  86. public static String doPost(String url, Map<String, Object> paramMap, Map<String, String> headers, String contentType, String charset) {
  87. CloseableHttpClient httpClient = null;
  88. CloseableHttpResponse httpResponse = null;
  89. String result = "";
  90. // 创建httpClient实例
  91. httpClient = HttpClients.createDefault();
  92. // 创建httpPost远程连接实例
  93. HttpPost httpPost = new HttpPost(url);
  94. // 配置请求参数实例
  95. // 连接主机服务超时时间、请求超时时间、数据读取超时时间
  96. RequestConfig requestConfig = RequestConfig.custom()
  97. .setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(10000)
  98. .build();
  99. // 为httpPost实例设置配置
  100. httpPost.setConfig(requestConfig);
  101. // 设置请求头
  102. httpPost.addHeader("Content-Type", contentType);
  103. if (headers != null && headers.size() > 0) {
  104. for(Map.Entry<String, String> entry : headers.entrySet()){
  105. httpPost.addHeader(entry.getKey(), entry.getValue());
  106. }
  107. }
  108. // 封装post请求参数
  109. if (null != paramMap && paramMap.size() > 0) {
  110. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  111. // 通过map集成entrySet方法获取entity
  112. Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
  113. // 循环遍历,获取迭代器
  114. Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
  115. while (iterator.hasNext()) {
  116. Map.Entry<String, Object> mapEntry = iterator.next();
  117. nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
  118. }
  119. // 为httpPost设置封装好的请求参数
  120. try {
  121. httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));
  122. } catch (UnsupportedEncodingException e) {
  123. e.printStackTrace();
  124. }
  125. }
  126. try {
  127. // httpClient对象执行post请求,并返回响应参数对象
  128. httpResponse = httpClient.execute(httpPost);
  129. // 从响应对象中获取响应内容
  130. HttpEntity entity = httpResponse.getEntity();
  131. result = org.apache.http.util.EntityUtils.toString(entity);
  132. } catch (ClientProtocolException e) {
  133. e.printStackTrace();
  134. } catch (IOException e) {
  135. e.printStackTrace();
  136. } finally {
  137. // 关闭资源
  138. if (null != httpResponse) {
  139. try {
  140. httpResponse.close();
  141. } catch (IOException e) {
  142. e.printStackTrace();
  143. }
  144. }
  145. if (null != httpClient) {
  146. try {
  147. httpClient.close();
  148. } catch (IOException e) {
  149. e.printStackTrace();
  150. }
  151. }
  152. }
  153. return result;
  154. }
  155. public static String doPostJSON(String url, String json) {
  156. return doPostJSON(url, json, null);
  157. }
  158. public static String doPostJSON(String url, String json, Map<String, String> headers) {
  159. CloseableHttpClient httpClient = null;
  160. try {
  161. httpClient = HttpClients.createDefault();
  162. HttpPost httpPost = new HttpPost(url);
  163. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(10000).build();
  164. // 为httpPost实例设置配置
  165. httpPost.setConfig(requestConfig);
  166. // 设置请求头
  167. httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
  168. if (headers != null && headers.size() > 0) {
  169. for (String key:headers.keySet()) {
  170. httpPost.addHeader(key, headers.get(key));
  171. }
  172. }
  173. // 解决中文乱码问题
  174. StringEntity stringEntity = new StringEntity(json, "UTF-8");
  175. stringEntity.setContentEncoding("UTF-8");
  176. httpPost.setEntity(stringEntity);
  177. ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
  178. @Override
  179. public String handleResponse(final HttpResponse response)
  180. throws ClientProtocolException, IOException {
  181. int status = response.getStatusLine().getStatusCode();
  182. if (status >= 200 && status < 300) {
  183. HttpEntity entity = response.getEntity();
  184. return entity != null ? EntityUtils.toString(entity) : null;
  185. } else {
  186. throw new ClientProtocolException("Unexpected response status: " + status);
  187. }
  188. }
  189. };
  190. return httpClient.execute(httpPost, responseHandler);
  191. } catch (Exception e) {
  192. e.printStackTrace();
  193. } finally {
  194. if (httpClient != null) {
  195. try {
  196. httpClient.close();
  197. } catch (IOException e) {
  198. e.printStackTrace();
  199. }
  200. }
  201. }
  202. return null;
  203. }
  204. public static String doPostGetLocation(String url, Map<String, Object> paramMap) {
  205. CloseableHttpResponse httpResponse = null;
  206. CloseableHttpClient httpClient = HttpClients.createDefault();
  207. HttpPost httpPost = new HttpPost(url);
  208. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(10000).build();
  209. // 为httpPost实例设置配置
  210. httpPost.setConfig(requestConfig);
  211. httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
  212. // 封装post请求参数
  213. if (null != paramMap && paramMap.size() > 0) {
  214. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  215. Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
  216. Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
  217. while (iterator.hasNext()) {
  218. Map.Entry<String, Object> mapEntry = iterator.next();
  219. nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
  220. }
  221. try {
  222. httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
  223. } catch (UnsupportedEncodingException e) {
  224. e.printStackTrace();
  225. }
  226. }
  227. try {
  228. // httpClient对象执行post请求,并返回响应参数对象
  229. httpResponse = httpClient.execute(httpPost);
  230. if (httpResponse.getStatusLine().getStatusCode() == 302 && httpResponse.getHeaders("Location").length > 0) {
  231. return httpResponse.getHeaders("Location")[0].getValue();
  232. }
  233. } catch (ClientProtocolException e) {
  234. e.printStackTrace();
  235. } catch (IOException e) {
  236. e.printStackTrace();
  237. } finally {
  238. // 关闭资源
  239. if (null != httpResponse) {
  240. try {
  241. httpResponse.close();
  242. } catch (IOException e) {
  243. e.printStackTrace();
  244. }
  245. }
  246. if (null != httpClient) {
  247. try {
  248. httpClient.close();
  249. } catch (IOException e) {
  250. e.printStackTrace();
  251. }
  252. }
  253. }
  254. return null;
  255. }
  256. }