个人随笔
目录
工具类:Java版HttpClient实现Http请求
2020-09-11 23:05:38

我们在开发过程中,经常需要进行http请求去调用各种接口和各种文档,比如微信公众号开发过程中,需要进程调用一些接口,像获取AccessToken,获取openid,QQ登录也要调用授权接口,微服务开发有时候也是直接用http请求来操作。

这里笔记一篇Java版本的Http请求工具类,主要是get请求和post请求,并且post请求参数主要是一个json字符串,具体怎么生成json字符串,大家可以用Gson把Map转即可。

Maveny依赖

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5.5</version>
  5. </dependency>
  6. <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
  7. <dependency>
  8. <groupId>org.apache.httpcomponents</groupId>
  9. <artifactId>httpcore</artifactId>
  10. <version>4.4.9</version>
  11. </dependency>

HttpUtils.java

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

注意:post请求传递的json参数,必须接口支持json参数传递,例如下面的springboot请求:

  1. @RequestMapping("/test")
  2. @ResponseBody
  3. public Map test(@RequestBody Model model) {
  4. System.out.println(model);
  5. Map<String,Object> map = new HashMap();
  6. map.put("哈哈哈", "狗子");
  7. return map;
  8. }
  1. @RequestBody 注解

如果单纯的用HttpServletRequest 来接收是接收不了的,如下:

  1. public List<Chapter> getChapters(HttpServletRequest request)

如果也想要接收,就不能传json模式,只能够Map模式。

 518

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


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

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