總結:實測有用。原作者:irokay,原文地址https://blog.csdn.net/irokay/article/details/78801307。
重點就是方法SSLContext。照着修改後的main方法實現就可以了。
HttpClient簡介
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/
請求步驟
許多需要後臺模擬請求的系統或者框架都用的是httpclient,使用HttpClient發送請求、接收響應很簡單,一般需要如下幾步即可:
- 創建CloseableHttpClient對象。
- 創建請求方法的實例,並指定請求URL。如果需要發送GET請求,創建HttpGet對象;如果需要發送POST請求,創建HttpPost對象。
- 如果需要發送請求參數,可可調用setEntity(HttpEntity entity)方法來設置請求參數。setParams方法已過時(4.4.1版本)。
- 調用HttpGet、HttpPost對象的setHeader(String name, String value)方法設置header信息,或者調用setHeaders(Header[] headers)設置一組header信息。
- 調用CloseableHttpClient對象的execute(HttpUriRequest request)發送請求,該方法返回一個CloseableHttpResponse。
- 調用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務器的響應內容。程序可通過該對象獲取服務器的響應內容;調用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務器的響應頭。
- 釋放連接。無論執行方法是否成功,都必須釋放連接
先看個官方HttpClient通過Http協議發送get請求,請求網頁內容的例子:
1.ClientWithResponseHandler.java
/*
*
* 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證書認證實現訪問。
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方法:
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的書的信息。
運行代碼:
獲取返回信息成功。