天天看點

Java用HttpClient3發送http/https協定get/post請求,發送map,jso

使用的是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. 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.                 return response.toString();  
  69.         }      
  70.          * 執行一個http/https post請求,傳回請求響應的文本資料 
  71.          * @param url       請求的URL位址 
  72.          * @param params    請求的查詢參數,可以為null 
  73.          * @param charset   字元集 
  74.          * @param pretty    是否美化 
  75.          * @return          傳回請求響應的文本資料 
  76.         public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) {  
  77.                     Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);  
  78.                 PostMethod method = new PostMethod(url);  
  79.                 //設定參數的字元集  
  80.                 method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,charset);  
  81.                 //設定post資料  
  82.                 if (params != null) {  
  83.                     //HttpMethodParams p = new HttpMethodParams();      
  84.                     for (Map.Entry<String, String> entry : params.entrySet()) {  
  85.                         //p.setParameter(entry.getKey(), entry.getValue());     
  86.                         method.setParameter(entry.getKey(), entry.getValue());  
  87.                     }  
  88.                     //method.setParams(p);  
  89.                                     response.append(line);   
  90.                     log.error("執行Post請求" + url + "時,發生異常!", e);  
  91.         }  
  92.          * 執行一個http/https post請求, 直接寫資料 json,xml,txt 
  93.         public static String writePost(String url, String content, String charset, boolean pretty) {   
  94.                         //設定請求頭部類型參數  
  95.                         //method.setRequestHeader("Content-Type","text/plain; charset=utf-8");//application/json,text/xml,text/plain  
  96.                         //method.setRequestBody(content); //InputStream,NameValuePair[],String  
  97.                         //RequestEntity是個接口,有很多實作類,發送不同類型的資料  
  98.                         RequestEntity requestEntity = new StringRequestEntity(content,"text/plain",charset);//application/json,text/xml,text/plain  
  99.                         method.setRequestEntity(requestEntity);  
  100.                         if (method.getStatusCode() == HttpStatus.SC_OK) {    
  101.                         }      
  102.                 } catch (Exception e) {  
  103.         public static void main(String[] args) {  
  104.             try {  
  105.                 String y = doGet("http://video.sina.com.cn/life/tips.html", null, "GBK", true);  
  106.                 System.out.println(y);  
  107. //              Map params = new HashMap();  
  108. //              params.put("param1", "value1");  
  109. //              params.put("json", "{\"aa\":\"11\"}");  
  110. //              String j = doPost("http://localhost/uplat/manage/test.do?reqCode=add", params, "UTF-8", true);  
  111. //              System.out.println(j);  
  112.             } catch (Exception e) {  
  113.                 // TODO Auto-generated catch block  
  114.                 e.printStackTrace();  
  115.             }  
  116. }  

MySSLProtocolSocketFactory

Java代碼 

  1. import java.net.InetAddress;  
  2. import java.net.InetSocketAddress;  
  3. import java.net.Socket;  
  4. import java.net.SocketAddress;  
  5. import java.net.UnknownHostException;  
  6. import java.security.KeyManagementException;  
  7. import java.security.NoSuchAlgorithmException;  
  8. import java.security.cert.CertificateException;  
  9. import java.security.cert.X509Certificate;  
  10. import javax.net.SocketFactory;  
  11. import javax.net.ssl.SSLContext;  
  12. import javax.net.ssl.TrustManager;  
  13. import javax.net.ssl.X509TrustManager;  
  14. import org.apache.commons.httpclient.ConnectTimeoutException;  
  15. import org.apache.commons.httpclient.params.HttpConnectionParams;  
  16. import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;  
  17. /** 
  18.  * author by lpp 
  19.  *  
  20.  * created at 2010-7-26 上午09:29:33 
  21.  */  
  22. public class MySSLProtocolSocketFactory implements ProtocolSocketFactory {  
  23.     private SSLContext sslcontext = null;  
  24.     private SSLContext createSSLContext() {  
  25.         SSLContext sslcontext = null;  
  26.         try {  
  27.             // sslcontext = SSLContext.getInstance("SSL");  
  28.             sslcontext = SSLContext.getInstance("TLS");  
  29.             sslcontext.init(null,  
  30.                     new TrustManager[] { new TrustAnyTrustManager() },  
  31.                     new java.security.SecureRandom());  
  32.         } catch (NoSuchAlgorithmException e) {  
  33.             e.printStackTrace();  
  34.         } catch (KeyManagementException e) {  
  35.         return sslcontext;  
  36.     }  
  37.     private SSLContext getSSLContext() {  
  38.         if (this.sslcontext == null) {  
  39.             this.sslcontext = createSSLContext();  
  40.         return this.sslcontext;  
  41.     public Socket createSocket(Socket socket, String host, int port, boolean autoClose)   
  42.             throws IOException, UnknownHostException {  
  43.         return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);  
  44.     public Socket createSocket(String host, int port) throws IOException, UnknownHostException {  
  45.         return getSSLContext().getSocketFactory().createSocket(host, port);  
  46.     public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)   
  47.         return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);  
  48.     public Socket createSocket(String host, int port, InetAddress localAddress,  
  49.             int localPort, HttpConnectionParams params) throws IOException,  
  50.             UnknownHostException, ConnectTimeoutException {  
  51.         if (params == null) {  
  52.             throw new IllegalArgumentException("Parameters may not be null");  
  53.         int timeout = params.getConnectionTimeout();  
  54.         SocketFactory socketfactory = getSSLContext().getSocketFactory();  
  55.         if (timeout == 0) {  
  56.             return socketfactory.createSocket(host, port, localAddress, localPort);  
  57.         } else {  
  58.             Socket socket = socketfactory.createSocket();  
  59.             SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);  
  60.             SocketAddress remoteaddr = new InetSocketAddress(host, port);  
  61.             socket.bind(localaddr);  
  62.             socket.connect(remoteaddr, timeout);  
  63.             return socket;  
  64.     // 自定義私有類  
  65.     private static class TrustAnyTrustManager implements X509TrustManager {  
  66.         public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
  67.         public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
  68.         public X509Certificate[] getAcceptedIssuers() {  
  69.             return new X509Certificate[] {};  
  70. }  
    1. 想要學習Java高架構、分布式架構、高可擴充、高性能、高并發、性能優化、Spring boot、Redis、ActiveMQ、Nginx、Mycat、Netty、Jvm大型分布式項目實戰學習架構師視訊免費擷取
    2. 架構群:835544715
    3. 點選連結加入群聊【JAVA進階架構】:https://jq.qq.com/?_wv=1027&k=5dbERkY