个人随笔
目录
调用微服务的Http请求工具类
2020-09-11 22:47:41

下面是Http get和post请求的工具类,在调用微服务接口的时候很实用,当然是外部调用微服务而不是服务之间的调用哦,服务之间的调用用feign比较方便,代码如下

  1. package cn.myforever.utils;
  2. import java.io.IOException;
  3. import java.security.KeyManagementException;
  4. import java.security.NoSuchAlgorithmException;
  5. import java.security.cert.CertificateException;
  6. import java.security.cert.X509Certificate;
  7. import java.util.ArrayList;
  8. import java.util.Arrays;
  9. import java.util.List;
  10. import java.util.Map;
  11. import javax.net.ssl.SSLContext;
  12. import javax.net.ssl.TrustManager;
  13. import javax.net.ssl.X509TrustManager;
  14. import org.apache.http.HttpEntity;
  15. import org.apache.http.HttpResponse;
  16. import org.apache.http.NameValuePair;
  17. import org.apache.http.client.HttpClient;
  18. import org.apache.http.client.config.AuthSchemes;
  19. import org.apache.http.client.config.CookieSpecs;
  20. import org.apache.http.client.config.RequestConfig;
  21. import org.apache.http.client.entity.UrlEncodedFormEntity;
  22. import org.apache.http.client.methods.HttpGet;
  23. import org.apache.http.client.methods.HttpPost;
  24. import org.apache.http.config.Registry;
  25. import org.apache.http.config.RegistryBuilder;
  26. import org.apache.http.conn.socket.ConnectionSocketFactory;
  27. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  28. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  29. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  30. import org.apache.http.entity.StringEntity;
  31. import org.apache.http.impl.client.CloseableHttpClient;
  32. import org.apache.http.impl.client.HttpClientBuilder;
  33. import org.apache.http.impl.client.HttpClients;
  34. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  35. import org.apache.http.message.BasicNameValuePair;
  36. import org.apache.http.util.EntityUtils;
  37. import org.slf4j.Logger;
  38. import org.slf4j.LoggerFactory;
  39. /**
  40. * setConnectTimeout:设置连接超时时间,单位毫秒。
  41. setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
  42. setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
  43. */
  44. /**
  45. * http请求工具类
  46. * @author lwh
  47. * @date 20181130
  48. */
  49. public class HttpUtils {
  50. private static final Integer CONNECT_TIMEOUT = 5000;//接超时时间,单位毫秒
  51. private static final Integer CONNECT_REQUEST_TIMEOUT = 1000;//从connect Manager(连接池)获取Connection 超时时间,单位毫秒。
  52. private static final Integer SOCKET_TIMEOUT = 5000;//响应时间
  53. private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
  54. /**
  55. * url get请求
  56. * @param url 访问的url
  57. * @return
  58. * @throws Exception
  59. */
  60. public static String doGet(String url) throws Exception {
  61. log.info("请求的url:"+url);
  62. HttpResponse response = doGet(url, null, CONNECT_TIMEOUT, CONNECT_REQUEST_TIMEOUT, SOCKET_TIMEOUT);
  63. String result = getString(response);
  64. log.info("返回的值:"+result);
  65. return result;
  66. }
  67. /**
  68. * url post请求
  69. * @param url 请求的url
  70. * @param json 传输的json信息,建议全部转换成json回来
  71. * @return
  72. * @throws Exception
  73. */
  74. public static String doPost(String url,String json) throws Exception {
  75. log.info("请求的url:"+url);
  76. HttpResponse response = doPost(url, json, CONNECT_TIMEOUT, CONNECT_REQUEST_TIMEOUT, SOCKET_TIMEOUT);
  77. String result = getString(response);
  78. log.info("返回的值:"+result);
  79. return result;
  80. }
  81. public static HttpResponse doGet(String path,Map<String, String> querys,Integer connectTimeout,Integer ConnectionRequestTimeout,Integer responseConnectTimeout)
  82. throws Exception {
  83. HttpClient httpClient = wrapClient(path);
  84. HttpGet request = new HttpGet(path);
  85. RequestConfig requestConfig = RequestConfig.custom()
  86. .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(ConnectionRequestTimeout)
  87. .setSocketTimeout(responseConnectTimeout).build();
  88. request.setConfig(requestConfig);
  89. return httpClient.execute(request);
  90. }
  91. public static HttpResponse doPost(String path,
  92. Map<String, Object> bodys,Integer connectTimeout,Integer ConnectionRequestTimeout,Integer responseConnectTimeout)
  93. throws Exception {
  94. HttpClient httpClient = wrapClient(path);
  95. HttpPost request = new HttpPost(path);
  96. RequestConfig requestConfig = RequestConfig.custom()
  97. .setConnectTimeout(5000).setConnectionRequestTimeout(1000)
  98. .setSocketTimeout(5000).build();
  99. request.setConfig(requestConfig);
  100. if (bodys != null) {
  101. List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
  102. for (String key : bodys.keySet()) {
  103. nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key).toString()));
  104. }
  105. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
  106. formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
  107. request.setEntity(formEntity);
  108. }
  109. return httpClient.execute(request);
  110. }
  111. public static HttpResponse doPost(String path,
  112. String jsonBody,Integer connectTimeout,Integer ConnectionRequestTimeout,Integer responseConnectTimeout)
  113. throws Exception {
  114. HttpClient httpClient = wrapClient(path);
  115. HttpPost request = new HttpPost(path);
  116. RequestConfig requestConfig = RequestConfig.custom()
  117. .setConnectTimeout(5000).setConnectionRequestTimeout(1000)
  118. .setSocketTimeout(5000).build();
  119. request.setConfig(requestConfig);
  120. if (jsonBody != null) {
  121. @SuppressWarnings("deprecation")
  122. StringEntity entity = new StringEntity(jsonBody, "text/xml", "utf-8");
  123. entity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
  124. request.setEntity(entity);
  125. }
  126. return httpClient.execute(request);
  127. }
  128. /**
  129. * 获取 HttpClient
  130. * @param path
  131. * @return
  132. */
  133. private static HttpClient wrapClient(String path) {
  134. HttpClient httpClient = HttpClientBuilder.create().build();
  135. if (path != null && path.startsWith("https://")) {
  136. return sslClient();
  137. }
  138. return httpClient;
  139. }
  140. /**
  141. * 在调用SSL之前需要重写验证方法,取消检测SSL
  142. * 创建ConnectionManager,添加Connection配置信息
  143. * @return HttpClient 支持https
  144. */
  145. private static HttpClient sslClient() {
  146. try {
  147. // 在调用SSL之前需要重写验证方法,取消检测SSL
  148. X509TrustManager trustManager = new X509TrustManager() {
  149. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
  150. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
  151. public X509Certificate[] getAcceptedIssuers() {
  152. return null;
  153. }
  154. };
  155. SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
  156. ctx.init(null, new TrustManager[] { trustManager }, null);
  157. SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
  158. // 创建Registry
  159. RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
  160. .setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,AuthSchemes.DIGEST))
  161. .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
  162. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  163. .register("http", PlainConnectionSocketFactory.INSTANCE)
  164. .register("https",socketFactory).build();
  165. // 创建ConnectionManager,添加Connection配置信息
  166. PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  167. CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
  168. .setDefaultRequestConfig(requestConfig).build();
  169. return closeableHttpClient;
  170. } catch (KeyManagementException ex) {
  171. throw new RuntimeException(ex);
  172. } catch (NoSuchAlgorithmException ex) {
  173. throw new RuntimeException(ex);
  174. }
  175. }
  176. public static String getString(HttpResponse httpResponse) throws IOException {
  177. HttpEntity entity = httpResponse.getEntity();
  178. String resp = EntityUtils.toString(entity, "UTF-8");
  179. return resp;
  180. }
  181. }

当然,需要在maven中引入如下内容

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.4</version>
  5. </dependency>
  6. <dependency>

其实上面的也不是我自己写的啦,也不知道是网上哪一个大神写的,忘记了,若是谁看到了,说侵权我就删了

 418

啊!这个可能是世界上最丑的留言输入框功能~


当然,也是最丑的留言列表

有疑问发邮件到 : suibibk@qq.com 侵权立删
Copyright : 个人随笔   备案号 : 粤ICP备18099399号-2