轉自:
http://www.java265.com/JavaCourse/202204/2939.html
HttpClient是一個java語言撰寫的包,
我們使用HttpClient可以非常方便的發送Http請求
它使基于Http協議請求內容變得非常簡單
HttpClient是Apache Jakarta Common下的子專案 它里面封裝了很多使用http協議訪問的工具,可用于高效訪問http
下文筆者講述基于HttpClient進行ss的示例分享,如下所示:
HttpClient進行ssl連接的示例分享,如下所示
實作思路:
1.定義一個keyStore物件,并讀取證書資訊
2.宣告一個SSLContext
3.定義一個SSLConnectionSocketFactory工廠
4.定義一個HttpGet請求體
5.execute執行運行
6.獲取回傳資訊
7.關閉連接
/**
* HttpClient連接SSL
*/
public void ssl() {
CloseableHttpClient httpclient = null;
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
try {
// 加載keyStore d:\\tomcat.keystore
trustStore.load(instream, "123456".toCharArray());
} catch (CertificateException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (Exception ignore) {
}
}
// 相信自己的CA和所有自簽名的證書
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
// 只允許使用TLSv1協議
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
// 創建http請求(get方式)
HttpGet httpget = new HttpGet("https://www.java265.com");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
System.out.println(EntityUtils.toString(entity));
EntityUtils.consume(entity);
}
} finally {
response.close();
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} finally {
if (httpclient != null) {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
參考資料:http://www.java265.com/JavaCourse/202204/2934.html HttpUtils工具類
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/500100.html
標籤:其他
