HttpClient发送Post请求

痛定思痛。 2022-09-11 15:19 390阅读 0赞

一.HttpClientUtil类,提供三个方法,分别是sendPostByForm,sendPostByJson,sendPostByXml

(1)sendPostByForm 处理 application/x-www-form-urlencoded格式报文的请求
(2)sendPostByJson 处理 application/json 格式报文的请求
(3)sendPostByXml 处理 text/xml 格式报文的请求
1.

  1. package com.harara.fund.util.http;
  2. import com.montnets.fund.constant.HttpConstant;
  3. import com.montnets.fund.factory.LogFactory;
  4. import com.montnets.fund.factory.service.LogService;
  5. import org.apache.http.Header;
  6. import org.apache.http.HttpEntity;
  7. import org.apache.http.HttpResponse;
  8. import org.apache.http.NameValuePair;
  9. import org.apache.http.client.HttpClient;
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;
  11. import org.apache.http.client.methods.HttpPost;
  12. import org.apache.http.entity.StringEntity;
  13. import org.apache.http.message.BasicHeader;
  14. import org.apache.http.message.BasicNameValuePair;
  15. import org.apache.http.util.EntityUtils;
  16. import java.io.IOException;
  17. import java.util.ArrayList;
  18. import java.util.Iterator;
  19. import java.util.List;
  20. import java.util.Map;
  21. /** * @author : chenlinyan * @version : 2.0 * @date : 2019/9/27 9:40 */
  22. public class HttpClientUtil {
  23. private static LogService logger = LogFactory.getLogger();
  24. /** * 通过post方式调用http接口 * @param url url路径 * @param jsonParam json格式的参数 * @param reSend 重发次数 * @return * @throws Exception */
  25. public static String sendPostByJson(String url, String jsonParam,int reSend) {
  26. //声明返回结果
  27. String result = "";
  28. //开始请求API接口时间
  29. long startTime=System.currentTimeMillis();
  30. //请求API接口的响应时间
  31. long endTime= 0L;
  32. HttpEntity httpEntity = null;
  33. HttpResponse httpResponse = null;
  34. HttpClient httpClient = null;
  35. try {
  36. // 创建连接
  37. httpClient = HttpClientFactory.getInstance().getHttpClient();
  38. // 设置请求头和报文
  39. HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
  40. Header header=new BasicHeader("Accept-Encoding",null);
  41. httpPost.setHeader(header);
  42. // 设置报文和通讯格式
  43. StringEntity stringEntity = new StringEntity(jsonParam,HttpConstant.UTF8_ENCODE);
  44. stringEntity.setContentEncoding(HttpConstant.UTF8_ENCODE);
  45. stringEntity.setContentType(HttpConstant.APPLICATION_JSON);
  46. httpPost.setEntity(stringEntity);
  47. logger.info("请求{}接口的参数为{}",url,jsonParam);
  48. //执行发送,获取相应结果
  49. httpResponse = httpClient.execute(httpPost);
  50. httpEntity= httpResponse.getEntity();
  51. result = EntityUtils.toString(httpEntity);
  52. } catch (Exception e) {
  53. logger.error("请求{}接口出现异常",url,e);
  54. if (reSend > 0) {
  55. logger.info("请求{}出现异常:{},进行重发。进行第{}次重发",url,e.getMessage(),(HttpConstant.REQ_TIMES-reSend +1));
  56. result = sendPostByJson(url, jsonParam, reSend - 1);
  57. if (result != null && !"".equals(result)) {
  58. return result;
  59. }
  60. }
  61. }finally {
  62. try {
  63. EntityUtils.consume(httpEntity);
  64. } catch (IOException e) {
  65. logger.error("http请求释放资源异常",e);
  66. }
  67. }
  68. //请求接口的响应时间
  69. endTime=System.currentTimeMillis();
  70. logger.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒",url,result,(endTime-startTime));
  71. return result;
  72. }
  73. /** * 通过post方式调用http接口 * @param url url路径 * @param map json格式的参数 * @param reSend 重发次数 * @return * @throws Exception */
  74. public static String sendPostByForm(String url, Map<String,String> map,int reSend) {
  75. //声明返回结果
  76. String result = "";
  77. //开始请求API接口时间
  78. long startTime=System.currentTimeMillis();
  79. //请求API接口的响应时间
  80. long endTime= 0L;
  81. HttpEntity httpEntity = null;
  82. UrlEncodedFormEntity entity = null;
  83. HttpResponse httpResponse = null;
  84. HttpClient httpClient = null;
  85. try {
  86. // 创建连接
  87. httpClient = HttpClientFactory.getInstance().getHttpClient();
  88. // 设置请求头和报文
  89. HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
  90. //设置参数
  91. List<NameValuePair> list = new ArrayList<NameValuePair>();
  92. Iterator iterator = map.entrySet().iterator();
  93. while(iterator.hasNext()){
  94. Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
  95. list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
  96. }
  97. entity = new UrlEncodedFormEntity(list,HttpConstant.UTF8_ENCODE);
  98. httpPost.setEntity(entity);
  99. logger.info("请求{}接口的参数为{}",url,map);
  100. //执行发送,获取相应结果
  101. httpResponse = httpClient.execute(httpPost);
  102. httpEntity= httpResponse.getEntity();
  103. result = EntityUtils.toString(httpEntity);
  104. } catch (Exception e) {
  105. logger.error("请求{}接口出现异常",url,e);
  106. if (reSend > 0) {
  107. logger.info("请求{}出现异常:{},进行重发。进行第{}次重发",url,e.getMessage(),(HttpConstant.REQ_TIMES-reSend +1));
  108. result = sendPostByForm(url, map, reSend - 1);
  109. if (result != null && !"".equals(result)) {
  110. return result;
  111. }
  112. }
  113. }finally {
  114. try {
  115. EntityUtils.consume(httpEntity);
  116. } catch (IOException e) {
  117. logger.error("http请求释放资源异常",e);
  118. }
  119. }
  120. //请求接口的响应时间
  121. endTime=System.currentTimeMillis();
  122. logger.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒",url,result,(endTime-startTime));
  123. return result;
  124. }
  125. /** * 通过post方式调用http接口 * @param url url路径 * @param xmlParam json格式的参数 * @param reSend 重发次数 * @return * @throws Exception */
  126. public static String sendPostByXml(String url, String xmlParam,int reSend) {
  127. //声明返回结果
  128. String result = "";
  129. //开始请求API接口时间
  130. long startTime = System.currentTimeMillis();
  131. //请求API接口的响应时间
  132. long endTime = 0L;
  133. HttpEntity httpEntity = null;
  134. HttpResponse httpResponse = null;
  135. HttpClient httpClient = null;
  136. try {
  137. // 创建连接
  138. httpClient = HttpClientFactory.getInstance().getHttpClient();
  139. // 设置请求头和报文
  140. HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
  141. StringEntity stringEntity = new StringEntity(xmlParam, HttpConstant.UTF8_ENCODE);
  142. stringEntity.setContentEncoding(HttpConstant.UTF8_ENCODE);
  143. stringEntity.setContentType(HttpConstant.TEXT_XML);
  144. httpPost.setEntity(stringEntity);
  145. logger.info("请求{}接口的参数为{}", url, xmlParam);
  146. //执行发送,获取相应结果
  147. httpResponse = httpClient.execute(httpPost);
  148. httpEntity = httpResponse.getEntity();
  149. result = EntityUtils.toString(httpEntity,HttpConstant.UTF8_ENCODE);
  150. } catch (Exception e) {
  151. logger.error("请求{}接口出现异常", url, e);
  152. if (reSend > 0) {
  153. logger.info("请求{}出现异常:{},进行重发。进行第{}次重发", url, e.getMessage(), (HttpConstant.REQ_TIMES - reSend + 1));
  154. result = sendPostByJson(url, xmlParam, reSend - 1);
  155. if (result != null && !"".equals(result)) {
  156. return result;
  157. }
  158. }
  159. } finally {
  160. try {
  161. EntityUtils.consume(httpEntity);
  162. } catch (IOException e) {
  163. logger.error("http请求释放资源异常", e);
  164. }
  165. //请求接口的响应时间
  166. endTime = System.currentTimeMillis();
  167. logger.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒", url, result, (endTime - startTime));
  168. return result;
  169. }
  170. }
  171. }

2.HttpClient工厂类HttpClientFactory,从工厂类获取HttpClient连接

  1. package com.harara.fund.util.http;
  2. import com.montnets.fund.constant.HttpConstant;
  3. import org.apache.http.client.HttpClient;
  4. import org.apache.http.client.config.RequestConfig;
  5. import org.apache.http.client.methods.HttpPost;
  6. import org.apache.http.config.Registry;
  7. import org.apache.http.config.RegistryBuilder;
  8. import org.apache.http.conn.socket.ConnectionSocketFactory;
  9. import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
  10. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  11. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  12. import org.apache.http.impl.client.HttpClients;
  13. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  14. import javax.net.ssl.SSLContext;
  15. import java.security.NoSuchAlgorithmException;
  16. /** * @author : harara * @version : 2.0 * @date : 2019/9/27 10:12 */
  17. public class HttpClientFactory {
  18. private static HttpClientFactory instance = null;
  19. private HttpClientFactory()
  20. {
  21. }
  22. public synchronized static HttpClientFactory getInstance()
  23. {
  24. if (instance == null)
  25. {
  26. instance = new HttpClientFactory();
  27. }
  28. return instance;
  29. }
  30. public synchronized HttpClient getHttpClient()
  31. {
  32. HttpClient httpClient = null;
  33. if (HttpConstant.IS_KEEP_ALIVE)
  34. {
  35. //获取长连接
  36. httpClient = new KeepAliveHttpClientBuilder().getKeepAliveHttpClient();
  37. } else
  38. {
  39. // 获取短连接
  40. httpClient = new HttpClientBuilder().getHttpClient();
  41. }
  42. return httpClient;
  43. }
  44. public HttpPost httpPost(String httpUrl)
  45. {
  46. HttpPost httpPost = null;
  47. httpPost = new HttpPost(httpUrl);
  48. if (HttpConstant.IS_KEEP_ALIVE)
  49. {
  50. // 设置为长连接,服务端判断有此参数就不关闭连接。
  51. httpPost.setHeader("Connection", "Keep-Alive");
  52. }
  53. return httpPost;
  54. }
  55. private static class KeepAliveHttpClientBuilder{
  56. private static HttpClient httpClient;
  57. /** * 获取http长连接 */
  58. private synchronized HttpClient getKeepAliveHttpClient()
  59. {
  60. if (httpClient == null)
  61. {
  62. LayeredConnectionSocketFactory sslsf = null;
  63. try {
  64. sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
  65. } catch (NoSuchAlgorithmException e) {
  66. e.printStackTrace();
  67. }
  68. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
  69. .<ConnectionSocketFactory> create().register("https", sslsf)
  70. .register("http", new PlainConnectionSocketFactory()).build();
  71. PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  72. cm.setMaxTotal(HttpConstant.MAX_TOTAL);
  73. cm.setDefaultMaxPerRoute(HttpConstant.MAX_CONN_PER_ROUTE);
  74. RequestConfig requestConfig = RequestConfig.custom()
  75. .setConnectTimeout(HttpConstant.CONNECT_TIMEOUT)
  76. .setSocketTimeout(HttpConstant.SOCKET_TIMEOUT).build();
  77. // 创建连接
  78. httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(cm).build();
  79. }
  80. return httpClient;
  81. }
  82. }
  83. private static class HttpClientBuilder{
  84. private HttpClient httpClient;
  85. /** * 获取http短连接 */
  86. private synchronized HttpClient getHttpClient()
  87. {
  88. if(httpClient == null){
  89. RequestConfig requestConfig = RequestConfig.custom()
  90. // 设置请求超时时间
  91. .setConnectTimeout(HttpConstant.CONNECT_TIMEOUT)
  92. // 设置响应超时时间
  93. .setSocketTimeout(HttpConstant.SOCKET_TIMEOUT).build();
  94. // 创建连接
  95. httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
  96. }
  97. return httpClient;
  98. }
  99. }
  100. }

3.HttpClient请求常量类

  1. package com.harara.fund.constant;
  2. /** * @author : harara * @version : 2.0 * @date : 2019/9/27 9:39 */
  3. public class HttpConstant {
  4. /**httpClient连接超时时间,单位毫秒 */
  5. public static final int CONNECT_TIMEOUT = 3*1000;
  6. /**httpClient请求获取数据的超时时间(即响应时间) 单位毫秒*/
  7. public static final int SOCKET_TIMEOUT = 10*1000;
  8. /**http连接池大小*/
  9. public static final int MAX_TOTAL = 10;
  10. /**分配给同一个route(路由)最大的并发连接数*/
  11. public static final int MAX_CONN_PER_ROUTE = 2;
  12. /**http连接是否是长连接*/
  13. public static final boolean IS_KEEP_ALIVE = true;
  14. /**调用接口失败默认重新调用次数*/
  15. public static final int REQ_TIMES = 3;
  16. /**utf-8编码*/
  17. public static final String UTF8_ENCODE = "UTF-8";
  18. /** application/json */
  19. public static final String APPLICATION_JSON = "application/json";
  20. /** text/xml */
  21. public static final String TEXT_XML = "text/xml";
  22. }
  23. > 通过一系列的操作,完成固定的功能。
  24. > 一系列的操作也是固定的,包括使用哪些类,哪些类的方法。

发表评论

表情:
评论列表 (有 0 条评论,390人围观)

还没有评论,来说两句吧...

相关阅读