1. 程式人生 > >HttpClient中post請求http、https示例

HttpClient中post請求http、https示例

HttpClient中post請求http、https示例

【轉自https://www.cnblogs.com/Mr-Rocker/p/6229652.html】
點選加入QQ群

【】HttpClient 是 Apache Jakarta Common 下的子專案,可以用來提供高效的、最新的、功能豐富的支援 HTTP 協議的客戶端程式設計工具包,並且它支援 HTTP 協議最新的版本和建議。

使用HttpClient傳送請求、接收響應很簡單,一般需要如下幾步即可:

  1. 建立CloseableHttpClient物件。
  2. 建立請求方法的例項,並指定請求URL。如果需要傳送GET請求,建立HttpGet物件;如果需要傳送POST請求,建立HttpPost物件。
  3. 如果需要傳送請求引數,可可呼叫setEntity(HttpEntity entity)方法來設定請求引數。setParams方法已過時(4.4.1版本)。
  4. 呼叫HttpGet、HttpPost物件的setHeader(String name, String value)方法設定header資訊,或者呼叫setHeaders(Header[] headers)設定一組header資訊。
  5. 呼叫CloseableHttpClient物件的execute(HttpUriRequest request)傳送請求,該方法返回一個CloseableHttpResponse。
  6. 呼叫HttpResponse的getEntity()方法可獲取HttpEntity物件,該物件包裝了伺服器的響應內容。程式可通過該物件獲取伺服器的響應內容;呼叫CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取伺服器的響應頭。
  7. 釋放連線。無論執行方法是否成功,都必須釋放連線

具體程式碼如下(HttpClient-4.4.1):

複製程式碼
/** 
 * 簡單httpclient例項
 * 
 * @author arron
 * @date 2015年11月11日 下午6:36:49 
 * @version 1.0 
 */
public class SimpleHttpClientDemo {

    /**
     * 模擬請求
     * 
     * @param url        資源地址
     * @param map    引數列表
     * 
@param encoding 編碼 * @return * @throws ParseException * @throws IOException */ public static String send(String url, Map<String,String> map,String encoding) throws ParseException, IOException{ String body = ""; //建立httpclient物件 CloseableHttpClient client = HttpClients.createDefault(); //建立post方式請求物件 HttpPost httpPost = new HttpPost(url); //裝填引數 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if(map!=null){ for (Entry<String, String> entry : map.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } //設定引數到請求物件中 httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); System.out.println("請求地址:"+url); System.out.println("請求引數:"+nvps.toString()); //設定header資訊 //指定報文頭【Content-type】、【User-Agent】 httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //執行請求操作,並拿到結果(同步阻塞) CloseableHttpResponse response = client.execute(httpPost); //獲取結果實體 HttpEntity entity = response.getEntity(); if (entity != null) { //按指定編碼轉換結果實體為String型別 body = EntityUtils.toString(entity, encoding); } EntityUtils.consume(entity); //釋放連結 response.close(); return body; } }
複製程式碼

對於HTTPS的訪問,採取繞過證書的策略:

複製程式碼
    /**
     * 繞過驗證
     *     
     * @return
     * @throws NoSuchAlgorithmException 
     * @throws KeyManagementException 
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 實現一個X509TrustManager介面,用於繞過驗證,不用修改裡面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }
複製程式碼

然後修改原來的send方法:

複製程式碼
    /**
     * 模擬請求
     * 
     * @param url        資源地址
     * @param map    引數列表
     * @param encoding    編碼
     * @return
     * @throws NoSuchAlgorithmException 
     * @throws KeyManagementException 
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    public static String send(String url, Map<String,String> map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
        String body = "";
        //採用繞過驗證的方式處理https請求
        SSLContext sslcontext = createIgnoreVerifySSL();
        
        // 設定協議http和https對應的處理socket連結工廠的物件
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

        //建立自定義的httpclient物件
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
//        CloseableHttpClient client = HttpClients.createDefault();
        
        //建立post方式請求物件
        HttpPost httpPost = new HttpPost(url);
        
        //裝填引數
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if(map!=null){
            for (Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        //設定引數到請求物件中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

        System.out.println("請求地址:"+url);
        System.out.println("請求引數:"+nvps.toString());
        
        //設定header資訊
        //指定報文頭【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        
        //執行請求操作,並拿到結果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpPost);
        //獲取結果實體
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定編碼轉換結果實體為String型別
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //釋放連結
        response.close();
        return body;
    }
複製程式碼

但是,如果是自己用jdk或者其他工具生成的證書,還是希望用其他方式認證自簽名的證書,這篇文章就來分享一下如何設定信任自簽名的證書。當然你也可以參考官網示例中。

要想信任自簽名的證書,必須得知道金鑰庫的路徑及金鑰庫的密碼。然後載入到程式來才可以。具體程式碼如下:

複製程式碼
    /**
     * 設定信任自簽名證書
     *     
     * @param keyStorePath        金鑰庫路徑
     * @param keyStorepass        金鑰庫密碼
     * @return
     */
    public static SSLContext custom(String keyStorePath, String keyStorepass){
        SSLContext sc = null;
        FileInputStream instream = null;
        KeyStore trustStore = null;
        try {
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            instream = new FileInputStream(new File(keyStorePath));
            trustStore.load(instream, keyStorepass.toCharArray());
            // 相信自己的CA和所有自簽名的證書
            sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
        } catch (KeyStoreException | NoSuchAlgorithmException| CertificateException | IOException | KeyManagementException e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (IOException e) {
            }
        }
        return sc;
    }
複製程式碼

然後修改原來的send方法:

複製程式碼
    /**
     * 模擬請求
     * 
     * @param url        資源地址
     * @param map    引數列表
     * @param encoding    編碼
     * @return
     * @throws ParseException
     * @throws IOException
     * @throws KeyManagementException 
     * @throws NoSuchAlgorithmException 
     * @throws ClientProtocolException 
     */
    public static String send(String url, Map<String,String> map,String encoding) throws ClientProtocolException, IOException {
        String body = "";
        
        //tomcat是我自己的金鑰庫的密碼,你可以替換成自己的
        //如果密碼為空,則用"nopassword"代替
        SSLContext sslcontext = custom("D:\\keys\\wsriakey", "tomcat");
        
        // 設定協議http和https對應的處理socket連結工廠的物件
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

        //建立自定義的httpclient物件
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
//        CloseableHttpClient client = HttpClients.createDefault();
        
        //建立post方式請求物件
        HttpPost httpPost = new HttpPost(url);
        
        //裝填引數
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if(map!=null){
            for (Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        //設定引數到請求物件中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

        System.out.println("請求地址:"+url);
        System.out.println("請求引數:"+nvps.toString());
        
        //設定header資訊
        //指定報文頭【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        
        //執行請求操作,並拿到結果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpPost);
        //獲取結果實體
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定編碼轉換結果實體為String型別
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //釋放連結
        response.close();
        return body;
    }