HttpClientUtils.java

  1. package utils;
  2. import java.io.IOException;
  3. import java.io.Serializable;
  4. import java.io.UnsupportedEncodingException;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Map.Entry;
  10. import java.util.Set;
  11. import org.apache.http.HttpStatus;
  12. import org.apache.http.NameValuePair;
  13. import org.apache.http.client.config.RequestConfig;
  14. import org.apache.http.client.entity.UrlEncodedFormEntity;
  15. import org.apache.http.client.methods.CloseableHttpResponse;
  16. import org.apache.http.client.methods.HttpDelete;
  17. import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
  18. import org.apache.http.client.methods.HttpGet;
  19. import org.apache.http.client.methods.HttpPost;
  20. import org.apache.http.client.methods.HttpPut;
  21. import org.apache.http.client.methods.HttpRequestBase;
  22. import org.apache.http.client.utils.URIBuilder;
  23. import org.apache.http.impl.client.CloseableHttpClient;
  24. import org.apache.http.impl.client.HttpClients;
  25. import org.apache.http.message.BasicNameValuePair;
  26. import org.apache.http.util.EntityUtils;
  27. /**
  28. * Description: httpClient工具类
  29. *
  30. * @author twx
  31. */
  32. public class HttpClientUtils {
  33. /**
  34. * 编码格式。发送编码格式统一用UTF-8
  35. */
  36. private static final String ENCODING = "UTF-8";
  37. /* 设置连接超时时间,单位毫秒。 */
  38. private static final int CONNECT_TIMEOUT = 6000;
  39. /* 请求获取数据的超时时间(即响应时间),单位毫秒。 */
  40. private static final int SOCKET_TIMEOUT = 6000;
  41. /**
  42. * 发送get请求;不带请求头和请求参数
  43. *
  44. * @param url 请求地址
  45. * @return
  46. * @throws Exception
  47. */
  48. public static HttpClientUtils.Result doGet(String url) throws Exception {
  49. return doGet(url, null, null);
  50. }
  51. /**
  52. * 发送get请求;带请求参数
  53. *
  54. * @param url 请求地址
  55. * @param params 请求参数集合
  56. * @return
  57. * @throws Exception
  58. */
  59. public static HttpClientUtils.Result doGet(String url, Map<String, String> params) throws Exception {
  60. return doGet(url, null, params);
  61. }
  62. /**
  63. * 发送get请求;带请求头和请求参数
  64. *
  65. * @param url 请求地址
  66. * @param headers 请求头集合
  67. * @param params 请求参数集合
  68. * @return
  69. * @throws Exception
  70. */
  71. public static HttpClientUtils.Result doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
  72. // 创建httpClient对象
  73. CloseableHttpClient httpClient = HttpClients.createDefault();
  74. // 创建访问的地址
  75. URIBuilder uriBuilder = new URIBuilder(url);
  76. if (params != null) {
  77. Set<Entry<String, String>> entrySet = params.entrySet();
  78. for (Entry<String, String> entry : entrySet) {
  79. uriBuilder.setParameter(entry.getKey(), entry.getValue());
  80. }
  81. }
  82. // 创建http对象
  83. HttpGet httpGet = new HttpGet(uriBuilder.build());
  84. /**
  85. * setConnectTimeout:设置连接超时时间,单位毫秒。
  86. * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
  87. * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
  88. * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
  89. */
  90. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
  91. httpGet.setConfig(requestConfig);
  92. // 设置请求头
  93. packageHeader(headers, httpGet);
  94. // 创建httpResponse对象
  95. CloseableHttpResponse httpResponse = null;
  96. try {
  97. // 执行请求并获得响应结果
  98. return getHttpClientResult(httpResponse, httpClient, httpGet);
  99. } finally {
  100. // 释放资源
  101. release(httpResponse, httpClient);
  102. }
  103. }
  104. /**
  105. * 发送post请求;不带请求头和请求参数
  106. *
  107. * @param url 请求地址
  108. * @return
  109. * @throws Exception
  110. */
  111. public static HttpClientUtils.Result doPost(String url) throws Exception {
  112. return doPost(url, null, null);
  113. }
  114. /**
  115. * 发送post请求;带请求参数
  116. *
  117. * @param url 请求地址
  118. * @param params 参数集合
  119. * @return
  120. * @throws Exception
  121. */
  122. public static HttpClientUtils.Result doPost(String url, Map<String, String> params) throws Exception {
  123. return doPost(url, null, params);
  124. }
  125. /**
  126. * 发送post请求;带请求头和请求参数
  127. *
  128. * @param url 请求地址
  129. * @param headers 请求头集合
  130. * @param params 请求参数集合
  131. * @return
  132. * @throws Exception
  133. */
  134. public static HttpClientUtils.Result doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
  135. // 创建httpClient对象
  136. CloseableHttpClient httpClient = HttpClients.createDefault();
  137. // 创建http对象
  138. HttpPost httpPost = new HttpPost(url);
  139. /**
  140. * setConnectTimeout:设置连接超时时间,单位毫秒。
  141. * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
  142. * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
  143. * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
  144. */
  145. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
  146. httpPost.setConfig(requestConfig);
  147. packageHeader(headers, httpPost);
  148. // 封装请求参数
  149. packageParam(params, httpPost);
  150. // 创建httpResponse对象
  151. CloseableHttpResponse httpResponse = null;
  152. try {
  153. // 执行请求并获得响应结果
  154. return getHttpClientResult(httpResponse, httpClient, httpPost);
  155. } finally {
  156. // 释放资源
  157. release(httpResponse, httpClient);
  158. }
  159. }
  160. /**
  161. * 发送put请求;不带请求参数
  162. *
  163. * @param url 请求地址
  164. * @return
  165. * @throws Exception
  166. */
  167. public static HttpClientUtils.Result doPut(String url) throws Exception {
  168. return doPut(url);
  169. }
  170. /**
  171. * 发送put请求;带请求参数
  172. *
  173. * @param url 请求地址
  174. * @param params 参数集合
  175. * @return
  176. * @throws Exception
  177. */
  178. public static HttpClientUtils.Result doPut(String url, Map<String, String> params) throws Exception {
  179. CloseableHttpClient httpClient = HttpClients.createDefault();
  180. HttpPut httpPut = new HttpPut(url);
  181. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
  182. httpPut.setConfig(requestConfig);
  183. packageParam(params, httpPut);
  184. CloseableHttpResponse httpResponse = null;
  185. try {
  186. return getHttpClientResult(httpResponse, httpClient, httpPut);
  187. } finally {
  188. release(httpResponse, httpClient);
  189. }
  190. }
  191. /**
  192. * 发送delete请求;不带请求参数
  193. *
  194. * @param url 请求地址
  195. * @return
  196. * @throws Exception
  197. */
  198. public static HttpClientUtils.Result doDelete(String url) throws Exception {
  199. CloseableHttpClient httpClient = HttpClients.createDefault();
  200. HttpDelete httpDelete = new HttpDelete(url);
  201. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
  202. httpDelete.setConfig(requestConfig);
  203. CloseableHttpResponse httpResponse = null;
  204. try {
  205. return getHttpClientResult(httpResponse, httpClient, httpDelete);
  206. } finally {
  207. release(httpResponse, httpClient);
  208. }
  209. }
  210. /**
  211. * 发送delete请求;带请求参数
  212. *
  213. * @param url 请求地址
  214. * @param params 参数集合
  215. * @return
  216. * @throws Exception
  217. */
  218. public static HttpClientUtils.Result doDelete(String url, Map<String, String> params) throws Exception {
  219. if (params == null) {
  220. params = new HashMap<String, String>();
  221. }
  222. params.put("_method", "delete");
  223. return doPost(url, params);
  224. }
  225. /**
  226. * Description: 封装请求头
  227. * @param params
  228. * @param httpMethod
  229. */
  230. public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
  231. // 封装请求头
  232. if (params != null) {
  233. Set<Entry<String, String>> entrySet = params.entrySet();
  234. for (Entry<String, String> entry : entrySet) {
  235. // 设置到请求头到HttpRequestBase对象中
  236. httpMethod.setHeader(entry.getKey(), entry.getValue());
  237. }
  238. }
  239. }
  240. /**
  241. * Description: 封装请求参数
  242. *
  243. * @param params
  244. * @param httpMethod
  245. * @throws UnsupportedEncodingException
  246. */
  247. public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
  248. throws UnsupportedEncodingException {
  249. // 封装请求参数
  250. if (params != null) {
  251. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  252. Set<Entry<String, String>> entrySet = params.entrySet();
  253. for (Entry<String, String> entry : entrySet) {
  254. nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  255. }
  256. // 设置到请求的http对象中
  257. httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
  258. }
  259. }
  260. /**
  261. * Description: 获得响应结果
  262. *
  263. * @param httpResponse
  264. * @param httpClient
  265. * @param httpMethod
  266. * @return
  267. * @throws Exception
  268. */
  269. public static HttpClientUtils.Result getHttpClientResult(CloseableHttpResponse httpResponse,
  270. CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
  271. // 执行请求
  272. httpResponse = httpClient.execute(httpMethod);
  273. // 获取返回结果
  274. if (httpResponse != null && httpResponse.getStatusLine() != null) {
  275. String content = "";
  276. if (httpResponse.getEntity() != null) {
  277. content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
  278. }
  279. return new HttpClientUtils.Result(httpResponse.getStatusLine().getStatusCode(), content);
  280. }
  281. return new HttpClientUtils.Result(HttpStatus.SC_INTERNAL_SERVER_ERROR);
  282. }
  283. /**
  284. * Description: 释放资源
  285. *
  286. * @param httpResponse
  287. * @param httpClient
  288. * @throws IOException
  289. */
  290. public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
  291. // 释放资源
  292. if (httpResponse != null) {
  293. httpResponse.close();
  294. }
  295. if (httpClient != null) {
  296. httpClient.close();
  297. }
  298. }
  299. /**
  300. * Description: 封装httpClient响应结果
  301. *
  302. * @author JourWon
  303. * @date Created on 2018年4月19日
  304. */
  305. public static class Result implements Serializable {
  306. private static final long serialVersionUID = 2168152194164783950L;
  307. /**
  308. * 响应状态码
  309. */
  310. private int code;
  311. /**
  312. * 响应数据
  313. */
  314. private String content;
  315. public Result() {
  316. }
  317. public Result(int code) {
  318. this.code = code;
  319. }
  320. public Result(String content) {
  321. this.content = content;
  322. }
  323. public Result(int code, String content) {
  324. this.code = code;
  325. this.content = content;
  326. }
  327. public int getCode() {
  328. return code;
  329. }
  330. public void setCode(int code) {
  331. this.code = code;
  332. }
  333. public String getContent() {
  334. return content;
  335. }
  336. public void setContent(String content) {
  337. this.content = content;
  338. }
  339. @Override
  340. public String toString() {
  341. return "HttpClientResult [code=" + code + ", content=" + content + "]";
  342. }
  343. }
  344. }