Java用HttpClient3傳送http/https協議get/post請求,傳送map,jso

架構之路發表於2018-10-17

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


相關文章