https://blog.csdn.net/irokay/article/details/78801307html
HTTP 協議多是如今 Internet 上使用得最多、最重要的協議了,愈來愈多的 Java 應用程序須要直接經過 HTTP 協議來訪問網絡資源。雖然在 JDK 的 java.net 包中已經提供了訪問 HTTP 協議的基本功能,可是對於大部分應用程序來講,JDK 庫自己提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,而且它支持 HTTP 協議最新的版本和建議。HttpClient 已經應用在不少的項目中,好比 Apache Jakarta 上很著名的另外兩個開源項目 Cactus 和 HTMLUnit 都使用了 HttpClient。更多信息請關注http://hc.apache.org/java
許多須要後臺模擬請求的系統或者框架都用的是httpclient,使用HttpClient發送請求、接收響應很簡單,通常須要以下幾步便可:apache
先看個官方HttpClient經過Http協議發送get請求,請求網頁內容的例子:編程
1.ClientWithResponseHandler.javaapi
/* * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.examples.client; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * This example demonstrates the use of the {@link ResponseHandler} to simplify * the process of processing the HTTP response and releasing associated resources. */ public class ClientWithResponseHandler { public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpGet httpget = new HttpGet("http://www.baidu.com/"); System.out.println("Executing request " + httpget.getRequestLine()); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse( final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpclient.execute(httpget, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); } finally { httpclient.close(); } } }
我把上述例子中的請求地址改成了「http://www.baidu.com/」,運行後控制檯能夠獲取百度首頁網頁內容:服務器
下面把地址改成https地址:https://www.baidu.com/,再次嘗試運行:
報錯了,提示unable to find valid certification path to requested target,沒法經過htpps認證。網絡
正規途徑,咱們須要將證書導入到密鑰庫中,如今咱們採起另一種方式:繞過https證書認證明現訪問。app
2.Method SSLContext框架
/** * 繞過驗證 * * @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; }
修改1中main方法:socket
public final static void main(String[] args) throws Exception { 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(); try{ //建立get方式請求對象 HttpGet get = new HttpGet("https://www.baidu.com/"); //指定報文頭Content-type、User-Agent get.setHeader("Content-type", "application/x-www-form-urlencoded"); get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2"); //執行請求操做,並拿到結果(同步阻塞) CloseableHttpResponse response = client.execute(get); //獲取結果實體 HttpEntity entity = response.getEntity(); if (entity != null) { //按指定編碼轉換結果實體爲String類型 body = EntityUtils.toString(entity, "UTF-8"); } EntityUtils.consume(entity); //釋放連接 response.close(); System.out.println("body:" + body); } finally{ client.close(); } }
運行代碼,獲取網頁內容成功!
同理,再嘗試下post請求:
public final static void main(String[] args) throws Exception { 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(); try{ //建立post方式請求對象 HttpPost httpPost = new HttpPost("https://api.douban.com/v2/book/1220562"); //指定報文頭Content-type、User-Agent httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2"); //執行請求操做,並拿到結果(同步阻塞) CloseableHttpResponse response = client.execute(httpPost); //獲取結果實體 HttpEntity entity = response.getEntity(); if (entity != null) { //按指定編碼轉換結果實體爲String類型 body = EntityUtils.toString(entity, "UTF-8"); } EntityUtils.consume(entity); //釋放連接 response.close(); System.out.println("body:" + body); }finally{ client.close(); } }
https地址以豆瓣的一個api爲例,得到ID爲1220562的書的信息。
運行代碼:
獲取返回信息成功。
本博客例子下載地址:
http://download.csdn.net/download/irokay/10158259
例子中包含以上工程代碼,以及所需HttpClient組件jar庫。
參考:
http://www.javashuo.com/article/p-vtyjicqx-dm.html
http://blog.csdn.net/xiaoxian8023/article/details/49865335
http://www.javashuo.com/article/p-vtyjicqx-dm.html