Java用HttpClient3发送http/https协议get/post请求

作者 : 开心源码 本文共8527个字,预计阅读时间需要22分钟 发布时间: 2022-05-14 共357人阅读

使用的是httpclient 3.1,

使用”httpclient”4的写法相对简单点,百度:httpclient https post

当不需要使用任何证书访问https网页时,只要配置信任任何证书

其中信任任何证书的类MySSLProtocolSocketFactory

主要代码:

HttpClient client = new HttpClient();

Protocol myhttps = new Protocol(“https”, new MySSLProtocolSocketFactory(), 443);

Protocol.registerProtocol(“https”, myhttps);

PostMethod method = new PostMethod(url);

HttpUtil

Java代码

  1. package com.urthinker.wxyh.util;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.util.Map;
  6. import org.apache.commons.httpclient.HttpClient;
  7. import org.apache.commons.httpclient.HttpMethod;
  8. import org.apache.commons.httpclient.HttpStatus;
  9. import org.apache.commons.httpclient.URIException;
  10. import org.apache.commons.httpclient.methods.GetMethod;
  11. import org.apache.commons.httpclient.methods.PostMethod;
  12. import org.apache.commons.httpclient.methods.RequestEntity;
  13. import org.apache.commons.httpclient.methods.StringRequestEntity;
  14. import org.apache.commons.httpclient.params.HttpMethodParams;
  15. import org.apache.commons.httpclient.protocol.Protocol;
  16. import org.apache.commons.httpclient.util.URIUtil;
  17. import org.apache.commons.lang.StringUtils;
  18. import org.apache.commons.logging.Log;
  19. import org.apache.commons.logging.LogFactory;
  20. /**
  21. * HTTP工具类
  22. * 发送http/https协议get/post请求,发送map,json,xml,txt数据
  23. *
  24. * @author happyqing 2016-5-20
  25. */
  26. public final class HttpUtil {
  27. private static Log log = LogFactory.getLog(HttpUtil.class);
  28. /**
  29. * 执行一个http/https get请求,返回请求响应的文本数据
  30. *
  31. * @param url 请求的URL地址
  32. * @param queryString 请求的查询参数,可以为null
  33. * @param charset 字符集
  34. * @param pretty 能否美化
  35. * @return 返回请求响应的文本数据
  36. */
  37. public static String doGet(String url, String queryString, String charset, boolean pretty) {
  38. StringBuffer response = new StringBuffer();
  39. HttpClient client = new HttpClient();
  40. if(url.startsWith(“https”)){
  41. //https请求
  42. Protocol myhttps = new Protocol(“https”, new MySSLProtocolSocketFactory(), 443);
  43. Protocol.registerProtocol(“https”, myhttps);
  44. }
  45. HttpMethod method = new GetMethod(url);
  46. try {
  47. if (StringUtils.isNotBlank(queryString))
  48. //对get请求参数编码,汉字编码后,就成为%式样的字符串
  49. method.setQueryString(URIUtil.encodeQuery(queryString));
  50. client.executeMethod(method);
  51. if (method.getStatusCode() == HttpStatus.SC_OK) {
  52. BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
  53. String line;
  54. while ((line = reader.readLine()) != null) {
  55. if (pretty)
  56. response.append(line).append(System.getProperty(“line.separator”));
  57. else
  58. response.append(line);
  59. }
  60. reader.close();
  61. }
  62. } catch (URIException e) {
  63. log.error(“执行Get请求时,编码查询字符串“” + queryString + “”发生异常!”, e);
  64. } catch (IOException e) {
  65. log.error(“执行Get请求” + url + “时,发生异常!”, e);
  66. } finally {
  67. method.releaseConnection();
  68. }
  69. return response.toString();
  70. }
  71. /**
  72. * 执行一个http/https post请求,返回请求响应的文本数据
  73. *
  74. * @param url 请求的URL地址
  75. * @param params 请求的查询参数,可以为null
  76. * @param charset 字符集
  77. * @param pretty 能否美化
  78. * @return 返回请求响应的文本数据
  79. */
  80. public static String doPost(String url, Map params, String charset, boolean pretty) {
  81. StringBuffer response = new StringBuffer();
  82. HttpClient client = new HttpClient();
  83. if(url.startsWith(“https”)){
  84. //https请求
  85. Protocol myhttps = new Protocol(“https”, new MySSLProtocolSocketFactory(), 443);
  86. Protocol.registerProtocol(“https”, myhttps);
  87. }
  88. PostMethod method = new PostMethod(url);
  89. //设置参数的字符集
  90. method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,charset);
  91. //设置post数据
  92. if (params != null) {
  93. //HttpMethodParams p = new HttpMethodParams();
  94. for (Map.Entry entry : params.entrySet()) {
  95. //p.setParameter(entry.getKey(), entry.getValue());
  96. method.setParameter(entry.getKey(), entry.getValue());
  97. }
  98. //method.setParams(p);
  99. }
  100. try {
  101. client.executeMethod(method);
  102. if (method.getStatusCode() == HttpStatus.SC_OK) {
  103. BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
  104. String line;
  105. while ((line = reader.readLine()) != null) {
  106. if (pretty)
  107. response.append(line).append(System.getProperty(“line.separator”));
  108. else
  109. response.append(line);
  110. }
  111. reader.close();
  112. }
  113. } catch (IOException e) {
  114. log.error(“执行Post请求” + url + “时,发生异常!”, e);
  115. } finally {
  116. method.releaseConnection();
  117. }
  118. return response.toString();
  119. }
  120. /**
  121. * 执行一个http/https post请求, 直接写数据 json,xml,txt
  122. *
  123. * @param url 请求的URL地址
  124. * @param params 请求的查询参数,可以为null
  125. * @param charset 字符集
  126. * @param pretty 能否美化
  127. * @return 返回请求响应的文本数据
  128. */
  129. public static String writePost(String url, String content, String charset, boolean pretty) {
  130. StringBuffer response = new StringBuffer();
  131. HttpClient client = new HttpClient();
  132. if(url.startsWith(“https”)){
  133. //https请求
  134. Protocol myhttps = new Protocol(“https”, new MySSLProtocolSocketFactory(), 443);
  135. Protocol.registerProtocol(“https”, myhttps);
  136. }
  137. PostMethod method = new PostMethod(url);
  138. try {
  139. //设置请求头部类型参数
  140. //method.setRequestHeader(“Content-Type”,”text/plain; charset=utf-8″);//application/json,text/xml,text/plain
  141. //method.setRequestBody(content); //InputStream,NameValuePair[],String
  142. //RequestEntity是个接口,有很多实现类,发送不同类型的数据
  143. RequestEntity requestEntity = new StringRequestEntity(content,”text/plain”,charset);//application/json,text/xml,text/plain
  144. method.setRequestEntity(requestEntity);
  145. client.executeMethod(method);
  146. if (method.getStatusCode() == HttpStatus.SC_OK) {
  147. BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
  148. String line;
  149. while ((line = reader.readLine()) != null) {
  150. if (pretty)
  151. response.append(line).append(System.getProperty(“line.separator”));
  152. else
  153. response.append(line);
  154. }
  155. reader.close();
  156. }
  157. } catch (Exception e) {
  158. log.error(“执行Post请求” + url + “时,发生异常!”, e);
  159. } finally {
  160. method.releaseConnection();
  161. }
  162. return response.toString();
  163. }
  164. public static void main(String[] args) {
  165. try {
  166. String y = doGet(“http://video.sina.com.cn/life/tips.html”, null, “GBK”, true);
  167. System.out.println(y);
  168. // Map params = new HashMap();
  169. // params.put(“param1”, “value1”);
  170. // params.put(“json”, “{\”aa\”:\”11\”}”);
  171. // String j = doPost(“http://localhost/uplat/manage/test.do?reqCode=add”, params, “UTF-8”, true);
  172. // System.out.println(j);
  173. } catch (Exception e) {
  174. // TODO Auto-generated catch block
  175. e.printStackTrace();
  176. }
  177. }
  178. }

MySSLProtocolSocketFactory

Java代码

  1. import java.io.IOException;
  2. import java.net.InetAddress;
  3. import java.net.InetSocketAddress;
  4. import java.net.Socket;
  5. import java.net.SocketAddress;
  6. import java.net.UnknownHostException;
  7. import java.security.KeyManagementException;
  8. import java.security.NoSuchAlgorithmException;
  9. import java.security.cert.CertificateException;
  10. import java.security.cert.X509Certificate;
  11. import javax.net.SocketFactory;
  12. import javax.net.ssl.SSLContext;
  13. import javax.net.ssl.TrustManager;
  14. import javax.net.ssl.X509TrustManager;
  15. import org.apache.commons.httpclient.ConnectTimeoutException;
  16. import org.apache.commons.httpclient.params.HttpConnectionParams;
  17. import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
  18. /**
  19. * author by lpp
  20. *
  21. * created at 2010-7-26 上午09:29:33
  22. */
  23. public class MySSLProtocolSocketFactory implements ProtocolSocketFactory {
  24. private SSLContext sslcontext = null;
  25. private SSLContext createSSLContext() {
  26. SSLContext sslcontext = null;
  27. try {
  28. // sslcontext = SSLContext.getInstance(“SSL”);
  29. sslcontext = SSLContext.getInstance(“TLS”);
  30. sslcontext.init(null,
  31. new TrustManager[] { new TrustAnyTrustManager() },
  32. new java.security.SecureRandom());
  33. } catch (NoSuchAlgorithmException e) {
  34. e.printStackTrace();
  35. } catch (KeyManagementException e) {
  36. e.printStackTrace();
  37. }
  38. return sslcontext;
  39. }
  40. private SSLContext getSSLContext() {
  41. if (this.sslcontext == null) {
  42. this.sslcontext = createSSLContext();
  43. }
  44. return this.sslcontext;
  45. }
  46. public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
  47. throws IOException, UnknownHostException {
  48. return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
  49. }
  50. public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
  51. return getSSLContext().getSocketFactory().createSocket(host, port);
  52. }
  53. public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
  54. throws IOException, UnknownHostException {
  55. return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
  56. }
  57. public Socket createSocket(String host, int port, InetAddress localAddress,
  58. int localPort, HttpConnectionParams params) throws IOException,
  59. UnknownHostException, ConnectTimeoutException {
  60. if (params == null) {
  61. throw new IllegalArgumentException(“Parameters may not be null”);
  62. }
  63. int timeout = params.getConnectionTimeout();
  64. SocketFactory socketfactory = getSSLContext().getSocketFactory();
  65. if (timeout == 0) {
  66. return socketfactory.createSocket(host, port, localAddress, localPort);
  67. } else {
  68. Socket socket = socketfactory.createSocket();
  69. SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
  70. SocketAddress remoteaddr = new InetSocketAddress(host, port);
  71. socket.bind(localaddr);
  72. socket.connect(remoteaddr, timeout);
  73. return socket;
  74. }
  75. }
  76. // 自己设置私有类
  77. private static class TrustAnyTrustManager implements X509TrustManager {
  78. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  79. }
  80. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  81. }
  82. public X509Certificate[] getAcceptedIssuers() {
  83. return new X509Certificate[] {};
  84. }
  85. }
  86. }

关注我:私信回复“666”获取往期Java高级架构资料、源码、笔记、视频

Dubbo、Redis、Netty、zookeeper、Spring cloud、分布式、高并发等架构

技术

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Java用HttpClient3发送http/https协议get/post请求

发表回复