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

  1. 云栖社区>
  2. 博客>
  3. 正文

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

架构之路 2018-10-17 22:10:16 浏览769
展开阅读全文

使用的是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

说到这里,也给大家推荐一个架构交流学习群:835544715,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,相信对于已经工作和遇到技术瓶颈的码友,在这个群里会有你需要的内容。

Java代码

  1. package com.urthinker.wxyh.util;  

  2.   

  3. import java.io.BufferedReader;  

  4. import java.io.IOException;  

  5. import java.io.InputStreamReader;  

  6. import java.util.Map;  

  7.   

  8. import org.apache.commons.httpclient.HttpClient;  

  9. import org.apache.commons.httpclient.HttpMethod;  

  10. import org.apache.commons.httpclient.HttpStatus;  

  11. import org.apache.commons.httpclient.URIException;  

  12. import org.apache.commons.httpclient.methods.GetMethod;  

  13. import org.apache.commons.httpclient.methods.PostMethod;  

  14. import org.apache.commons.httpclient.methods.RequestEntity;  

  15. import org.apache.commons.httpclient.methods.StringRequestEntity;  

  16. import org.apache.commons.httpclient.params.HttpMethodParams;  

  17. import org.apache.commons.httpclient.protocol.Protocol;  

  18. import org.apache.commons.httpclient.util.URIUtil;  

  19. import org.apache.commons.lang.StringUtils;  

  20. import org.apache.commons.logging.Log;  

  21. import org.apache.commons.logging.LogFactory;  

  22.     

  23. /**    

  24. * HTTP工具类 

  25. * 发送http/https协议get/post请求,发送map,json,xml,txt数据 

  26. *    

  27. * @author happyqing 2016-5-20   

  28. */      

  29. public final class HttpUtil {      

  30.         private static Log log = LogFactory.getLog(HttpUtil.class);      

  31.     

  32.         /** 

  33.          * 执行一个http/https get请求,返回请求响应的文本数据 

  34.          *  

  35.          * @param url           请求的URL地址 

  36.          * @param queryString   请求的查询参数,可以为null 

  37.          * @param charset       字符集 

  38.          * @param pretty        是否美化 

  39.          * @return              返回请求响应的文本数据 

  40.          */  

  41.         public static String doGet(String url, String queryString, String charset, boolean pretty) {     

  42.                 StringBuffer response = new StringBuffer();  

  43.                 HttpClient client = new HttpClient();  

  44.                 if(url.startsWith("https")){  

  45.                     //https请求  

  46.                     Protocol myhttps = new Protocol("https"new MySSLProtocolSocketFactory(), 443);     

  47.                     Protocol.registerProtocol("https", myhttps);  

  48.                 }  

  49.                 HttpMethod method = new GetMethod(url);  

  50.                 try {  

  51.                         if (StringUtils.isNotBlank(queryString))      

  52.                             //对get请求参数编码,汉字编码后,就成为%式样的字符串  

  53.                             method.setQueryString(URIUtil.encodeQuery(queryString));  

  54.                         client.executeMethod(method);  

  55.                         if (method.getStatusCode() == HttpStatus.SC_OK) {  

  56.                             BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));  

  57.                             String line;  

  58.                             while ((line = reader.readLine()) != null) {  

  59.                                 if (pretty)  

  60.                                     response.append(line).append(System.getProperty("line.separator"));  

  61.                                 else  

  62.                                     response.append(line);  

  63.                             }  

  64.                             reader.close();  

  65.                         }  

  66.                 } catch (URIException e) {  

  67.                     log.error("执行Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);  

  68.                 } catch (IOException e) {  

  69.                     log.error("执行Get请求" + url + "时,发生异常!", e);  

  70.                 } finally {  

  71.                     method.releaseConnection();  

  72.                 }  

  73.                 return response.toString();  

  74.         }      

  75.     

  76.         /** 

  77.          * 执行一个http/https post请求,返回请求响应的文本数据 

  78.          *  

  79.          * @param url       请求的URL地址 

  80.          * @param params    请求的查询参数,可以为null 

  81.          * @param charset   字符集 

  82.          * @param pretty    是否美化 

  83.          * @return          返回请求响应的文本数据 

  84.          */  

  85.         public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) {  

  86.                 StringBuffer response = new StringBuffer();  

  87.                 HttpClient client = new HttpClient();  

  88.                 if(url.startsWith("https")){  

  89.                     //https请求  

  90.                     Protocol myhttps = new Protocol("https"new MySSLProtocolSocketFactory(), 443);  

  91.                     Protocol.registerProtocol("https", myhttps);  

  92.                 }  

  93.                 PostMethod method = new PostMethod(url);  

  94.                 //设置参数的字符集  

  95.                 method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,charset);  

  96.                 //设置post数据  

  97.                 if (params != null) {  

  98.                     //HttpMethodParams p = new HttpMethodParams();      

  99.                     for (Map.Entry<String, String> entry : params.entrySet()) {  

  100.                         //p.setParameter(entry.getKey(), entry.getValue());     

  101.                         method.setParameter(entry.getKey(), entry.getValue());  

  102.                     }  

  103.                     //method.setParams(p);  

  104.                 }  

  105.                 try {  

  106.                         client.executeMethod(method);  

  107.                         if (method.getStatusCode() == HttpStatus.SC_OK) {  

  108.                             BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));  

  109.                             String line;  

  110.                             while ((line = reader.readLine()) != null) {  

  111.                                 if (pretty)  

  112.                                     response.append(line).append(System.getProperty("line.separator"));  

  113.                                 else  

  114.                                     response.append(line);   

  115.                             }  

  116.                             reader.close();  

  117.                         }  

  118.                 } catch (IOException e) {  

  119.                     log.error("执行Post请求" + url + "时,发生异常!", e);  

  120.                 } finally {  

  121.                     method.releaseConnection();  

  122.                 }  

  123.                 return response.toString();  

  124.         }  

  125.           

  126.         /** 

  127.          * 执行一个http/https post请求, 直接写数据 json,xml,txt 

  128.          *  

  129.          * @param url       请求的URL地址 

  130.          * @param params    请求的查询参数,可以为null 

  131.          * @param charset   字符集 

  132.          * @param pretty    是否美化 

  133.          * @return          返回请求响应的文本数据 

  134.          */  

  135.         public static String writePost(String url, String content, String charset, boolean pretty) {   

  136.                 StringBuffer response = new StringBuffer();  

  137.                 HttpClient client = new HttpClient();  

  138.                 if(url.startsWith("https")){  

  139.                     //https请求  

  140.                     Protocol myhttps = new Protocol("https"new MySSLProtocolSocketFactory(), 443);  

  141.                     Protocol.registerProtocol("https", myhttps);  

  142.                 }  

  143.                 PostMethod method = new PostMethod(url);  

  144.                 try {  

  145.                         //设置请求头部类型参数  

  146.                         //method.setRequestHeader("Content-Type","text/plain; charset=utf-8");//application/json,text/xml,text/plain  

  147.                         //method.setRequestBody(content); //InputStream,NameValuePair[],String  

  148.                         //RequestEntity是个接口,有很多实现类,发送不同类型的数据  

  149.                         RequestEntity requestEntity = new StringRequestEntity(content,"text/plain",charset);//application/json,text/xml,text/plain  

  150.                         method.setRequestEntity(requestEntity);  

  151.                         client.executeMethod(method);  

  152.                         if (method.getStatusCode() == HttpStatus.SC_OK) {    

  153.                             BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));  

  154.                             String line;  

  155.                             while ((line = reader.readLine()) != null) {  

  156.                                 if (pretty)  

  157.                                     response.append(line).append(System.getProperty("line.separator"));  

  158.                                 else  

  159.                                     response.append(line);  

  160.                             }  

  161.                             reader.close();  

  162.                         }      

  163.                 } catch (Exception e) {  

  164.                     log.error("执行Post请求" + url + "时,发生异常!", e);  

  165.                 } finally {  

  166.                     method.releaseConnection();  

  167.                 }  

  168.                 return response.toString();  

  169.         }  

  170.     

  171.         public static void main(String[] args) {  

  172.             try {  

  173.                 String y = doGet("http://video.sina.com.cn/life/tips.html"null"GBK"true);  

  174.                 System.out.println(y);  

  175. //              Map params = new HashMap();  

  176. //              params.put("param1", "value1");  

  177. //              params.put("json", "{\"aa\":\"11\"}");  

  178. //              String j = doPost("http://localhost/uplat/manage/test.do?reqCode=add", params, "UTF-8", true);  

  179. //              System.out.println(j);  

  180.   

  181.             } catch (Exception e) {  

  182.                 // TODO Auto-generated catch block  

  183.                 e.printStackTrace();  

  184.             }  

  185.         }  

  186.   

  187. }  

 

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.   

  12. import javax.net.SocketFactory;  

  13. import javax.net.ssl.SSLContext;  

  14. import javax.net.ssl.TrustManager;  

  15. import javax.net.ssl.X509TrustManager;  

  16.   

  17. import org.apache.commons.httpclient.ConnectTimeoutException;  

  18. import org.apache.commons.httpclient.params.HttpConnectionParams;  

  19. import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;  

  20.   

  21. /** 

  22.  * author by lpp 

  23.  *  

  24.  * created at 2010-7-26 上午09:29:33 

  25.  */  

  26. public class MySSLProtocolSocketFactory implements ProtocolSocketFactory {  

  27.   

  28.     private SSLContext sslcontext = null;  

  29.   

  30.     private SSLContext createSSLContext() {  

  31.         SSLContext sslcontext = null;  

  32.         try {  

  33.             // sslcontext = SSLContext.getInstance("SSL");  

  34.             sslcontext = SSLContext.getInstance("TLS");  

  35.             sslcontext.init(null,  

  36.                     new TrustManager[] { new TrustAnyTrustManager() },  

  37.                     new java.security.SecureRandom());  

  38.         } catch (NoSuchAlgorithmException e) {  

  39.             e.printStackTrace();  

  40.         } catch (KeyManagementException e) {  

  41.             e.printStackTrace();  

  42.         }  

  43.         return sslcontext;  

  44.     }  

  45.   

  46.     private SSLContext getSSLContext() {  

  47.         if (this.sslcontext == null) {  

  48.             this.sslcontext = createSSLContext();  

  49.         }  

  50.         return this.sslcontext;  

  51.     }  

  52.   

  53.     public Socket createSocket(Socket socket, String host, int port, boolean autoClose)   

  54.             throws IOException, UnknownHostException {  

  55.         return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);  

  56.     }  

  57.   

  58.     public Socket createSocket(String host, int port) throws IOException, UnknownHostException {  

  59.         return getSSLContext().getSocketFactory().createSocket(host, port);  

  60.     }  

  61.   

  62.     public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)   

  63.             throws IOException, UnknownHostException {  

  64.         return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);  

  65.     }  

  66.   

  67.     public Socket createSocket(String host, int port, InetAddress localAddress,  

  68.             int localPort, HttpConnectionParams params) throws IOException,  

  69.             UnknownHostException, ConnectTimeoutException {  

  70.         if (params == null) {  

  71.             throw new IllegalArgumentException("Parameters may not be null");  

  72.         }  

  73.         int timeout = params.getConnectionTimeout();  

  74.         SocketFactory socketfactory = getSSLContext().getSocketFactory();  

  75.         if (timeout == 0) {  

  76.             return socketfactory.createSocket(host, port, localAddress, localPort);  

  77.         } else {  

  78.             Socket socket = socketfactory.createSocket();  

  79.             SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);  

  80.             SocketAddress remoteaddr = new InetSocketAddress(host, port);  

  81.             socket.bind(localaddr);  

  82.             socket.connect(remoteaddr, timeout);  

  83.             return socket;  

  84.         }  

  85.     }  

  86.   

  87.     // 自定义私有类  

  88.     private static class TrustAnyTrustManager implements X509TrustManager {  

  89.   

  90.         public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  

  91.         }  

  92.   

  93.         public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  

  94.         }  

  95.   

  96.         public X509Certificate[] getAcceptedIssuers() {  

  97.             return new X509Certificate[] {};  

  98.         }  

  99.     }  

  100.   

  101. }  

    1. 想要学习Java高架构、分布式架构、高可扩展、高性能、高并发、性能优化、Spring boot、Redis、ActiveMQ、Nginx、Mycat、Netty、Jvm大型分布式项目实战学习架构师视频免费获取

    2. 架构群:835544715

    3. 点击链接加入群聊【JAVA高级架构】:https://jq.qq.com/?_wv=1027&k=5dbERkY

网友评论

登录后评论
0/500
评论
架构之路
+ 关注