在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

关于Java去连接HTTP地址的操作

2017-2-7 13:41| 发布者: zhangjf| 查看: 546| 评论: 0

摘要: 使用HTTPClient进行操作,可以忽略SSL /** * @author Kai * @Date 2015-7-28 19:47:16 */public class HTTPClient { //HTTP请求读取超时时间 private static final int SOCKET_TIME_OUT = 5000; //HTTP请求 ...

使用HTTPClient进行操作,可以忽略SSL

  1. /**
  2. * @author Kai
  3. * @Date 2015-7-28 19:47:16
  4. */
  5. public class HTTPClient {
  6. //HTTP请求读取超时时间
  7. private static final int SOCKET_TIME_OUT = 5000;
  8. //HTTP请求连接时间
  9. private static final int CONNECT_TIME_OUT = 5000;
  10. //请求重试次数
  11. private static final int RETRY_TIMES = 3;
  12. /**
  13. *
  14. * @param address 请求地址
  15. * @param method 请求方式
  16. * @param params 请求参数
  17. * @param paramSendType 发送类型
  18. * @param cookies 设置cookies值发送
  19. * @return
  20. */
  21. public String request(String address, String method, String params, String paramSendType, String cookies) {
  22. address = address.trim();
  23. CloseableHttpResponse closeableHttpResponse = null;
  24. if (SupportProtocol.HTTP_METHOD_GET.equalsIgnoreCase(method)) {
  25. closeableHttpResponse = this.GET(address, params, paramSendType, cookies);
  26. } else if (SupportProtocol.HTTP_METHOD_POST.equalsIgnoreCase(method)) {
  27. closeableHttpResponse = this.POST(address, params, paramSendType, cookies);
  28. } else if (SupportProtocol.HTTP_METHOD_PUT.equalsIgnoreCase(method)) {
  29. closeableHttpResponse = this.PUT(address, params, paramSendType, cookies);
  30. } else {
  31. closeableHttpResponse = this.POST(address, params, paramSendType, cookies);
  32. }
  33. return this.buildReponseMsg(closeableHttpResponse);
  34. }
  35. private CloseableHttpResponse PUT(String address, String params, String paramSendType, String cookies) {
  36. try {
  37. URI uri = URI.create(address);
  38. HttpPut httpPut = new HttpPut(uri);
  39. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
  40. httpPut.setConfig(requestConfig);
  41. if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {
  42. httpPut.setHeader("Content-Type", "application/json; charset=UTF-8");
  43. StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON);
  44. httpPut.setEntity(entity);
  45. } else if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {
  46. httpPut.setHeader("Content-Type", "application/xml; charset=UTF-8");
  47. StringEntity entity = new StringEntity(params, ContentType.APPLICATION_XML);
  48. httpPut.setEntity(entity);
  49. } else {
  50. httpPut.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  51. StringEntity entity = new StringEntity(params, ContentType.APPLICATION_FORM_URLENCODED);
  52. httpPut.setEntity(entity);
  53. }
  54. if (StrUtil.isNotEmpty(cookies)) {
  55. httpPut.setHeader("Cookie", cookies);
  56. }
  57. CloseableHttpClient httpClient = HttpClients.createDefault();
  58. if (address.toLowerCase().startsWith("https")) {
  59. httpClient = this.createSSLClientDefault();
  60. }
  61. return httpClient.execute(httpPut);
  62. } catch (Exception ex) {
  63. LogUtil.error(ex);
  64. }
  65. return null;
  66. }
  67. private CloseableHttpResponse GET(String address, String params, String paramSendType, String cookies) {
  68. try {
  69. URI uri;
  70. if (EmptyUtil.isNotEmpty(params)) {
  71. uri = URI.create(String.format("%s?%s", address, params));
  72. } else {
  73. uri = URI.create(address);
  74. }
  75. HttpGet httpGet = new HttpGet(uri);
  76. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
  77. httpGet.setConfig(requestConfig);
  78. if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {
  79. httpGet.setHeader("Content-Type", "application/json; charset=UTF-8");
  80. } else if (SupportProtocol.SUPPORT_XML.equalsIgnoreCase(paramSendType)) {
  81. httpGet.setHeader("Content-Type", "application/xml; charset=UTF-8");
  82. } else {
  83. httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  84. }
  85. if (StrUtil.isNotEmpty(cookies)) {
  86. httpGet.setHeader("Cookie", cookies);
  87. }
  88. CloseableHttpClient httpClient = HttpClients.createDefault();
  89. if (address.toLowerCase().startsWith("https")) {
  90. httpClient = this.createSSLClientDefault();
  91. }
  92. return httpClient.execute(httpGet);
  93. } catch (Exception ex) {
  94. LogUtil.error(ex);
  95. }
  96. return null;
  97. }
  98. private CloseableHttpResponse POST(String address, String params, String paramSendType, String cookies) {
  99. try {
  100. URI uri = URI.create(address);
  101. HttpPost httpPost = new HttpPost(uri);
  102. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
  103. httpPost.setConfig(requestConfig);
  104. if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {
  105. httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
  106. StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON);
  107. httpPost.setEntity(entity);
  108. } else if (SupportProtocol.SUPPORT_XML.equalsIgnoreCase(paramSendType)) {
  109. httpPost.setHeader("Content-Type", "application/xml; charset=UTF-8");
  110. StringEntity entity = new StringEntity(params, ContentType.APPLICATION_XML);
  111. httpPost.setEntity(entity);
  112. } else {
  113. httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  114. StringEntity entity = new StringEntity(params, ContentType.APPLICATION_FORM_URLENCODED);
  115. httpPost.setEntity(entity);
  116. }
  117. if (StrUtil.isNotEmpty(cookies)) {
  118. httpPost.setHeader("Cookie", cookies);
  119. }
  120. CloseableHttpClient httpClient = HttpClients.createDefault();
  121. if (address.toLowerCase().startsWith("https")) {
  122. httpClient = this.createSSLClientDefault();
  123. }
  124. return httpClient.execute(httpPost);
  125. } catch (Exception ex) {
  126. LogUtil.error(ex);
  127. }
  128. return null;
  129. }
  130. private CloseableHttpClient createSSLClientDefault() {
  131. try {
  132. SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
  133. @Override
  134. public boolean isTrusted(X509Certificate[] chain,
  135. String authType) throws CertificateException {
  136. return true;
  137. }
  138. }).build();
  139. SSLSocketFactory ssf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  140. return HttpClients.custom().setSSLSocketFactory(ssf).build();
  141. } catch (Exception e) {
  142. LogUtil.error(e.getMessage());
  143. }
  144. return HttpClients.createDefault();
  145. }
  146. private String buildReponseMsg(CloseableHttpResponse closeableHttpResponse) {
  147. if (closeableHttpResponse == null) {
  148. return null;
  149. }
  150. try {
  151. int code = closeableHttpResponse.getStatusLine().getStatusCode();
  152. String msg = EntityUtils.toString(closeableHttpResponse.getEntity());
  153. if (code == HttpStatus.SC_OK) {
  154. return msg;
  155. }
  156. } catch (Exception ex) {
  157. LogUtil.error(ex);
  158. }
  159. return null;
  160. }
  161. }
复制代码


使用URLConnection读取数据,访问HTTPS貌似有问题

  1. package com.k.ctc.http;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.io.OutputStreamWriter;
  5. import java.io.UnsupportedEncodingException;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8. import java.net.URLEncoder;
  9. import java.util.Map;
  10. /**
  11. *
  12. * @author Kai
  13. */
  14. public class Connector {
  15. public String GET(String address, Map<String, String> params) throws Exception {
  16. String param = this.buildParams(params);
  17. URL url = new URL(address + "?" + param);
  18. URLConnection conn = url.openConnection();
  19. return this.readData(conn);
  20. }
  21. public String GET(String address, String params) throws Exception {
  22. URL url = new URL(address + "?" + params);
  23. URLConnection conn = url.openConnection();
  24. return this.readData(conn);
  25. }
  26. public String POST(String address, Map<String, String> params) throws Exception {
  27. String param = this.buildParams(params);
  28. URL url = new URL(address);
  29. URLConnection conn = url.openConnection();
  30. this.postData(conn, param);
  31. return this.readData(conn);
  32. }
  33. public String POST(String address, String param) throws Exception {
  34. URL url = new URL(address);
  35. URLConnection conn = url.openConnection();
  36. this.postData(conn, param);
  37. return this.readData(conn);
  38. }
  39. private String buildParams(Map<String, String> params) throws UnsupportedEncodingException {
  40. StringBuilder sb = new StringBuilder();
  41. for (Map.Entry<String, String> param : params.entrySet()) {
  42. sb.append(param.getKey()).append("=");
  43. sb.append(URLEncoder.encode(param.getValue(), "UTF-8"));
  44. sb.append("&");
  45. }
  46. return sb.toString();
  47. }
  48. private void postData(final URLConnection conn, String requestData) throws Exception {
  49. conn.setDoOutput(true);
  50. OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
  51. wr.write(requestData);
  52. wr.flush();
  53. wr.close();
  54. }
  55. private String readData(final URLConnection conn) throws Exception {
  56. String responseData = "";
  57. BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
  58. String line;
  59. while ((line = rd.readLine()) != null) {
  60. responseData += line;
  61. }
  62. responseData = new String(responseData.getBytes(), "UTF-8");
  63. rd.close();
  64. return responseData;
  65. }
  66. }
复制代码


做个代码记录 Maven引用

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.4</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.httpcomponents</groupId>
  8. <artifactId>httpcore</artifactId>
  9. <version>4.4</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.httpcomponents</groupId>
  13. <artifactId>httpcore-nio</artifactId>
  14. <version>4.4</version>
  15. </dependency>
复制代码



来自: http://my.oschina.net/Kxvz/blog/599039

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-9 09:43

Copyright 2015-2025 djqfx

返回顶部