在作業中需要java httpClient訪問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) {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
/**
* 模擬請求
*
* @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();
//創建自定義的httpclient物件
SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(scsf).build();// CloseableHttpClient client = HttpClients.createDefault();
//創建post方式請求物件
HttpPost httpPost = new HttpPost(url);
//裝填引數
List<NameValuePair> nvps = new ArrayList<>();
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);
//設定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 = httpclient.execute(httpPost);
//獲取結果物體
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定編碼轉換結果物體為String型別
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//釋放鏈接
response.close();
return body;
}
參考資料:1.https://www.kancloud.cn/longxuan/httpclient-arron/117503
2.https://www.jianshu.com/p/e70ea8754506
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458469.html
標籤:Java
上一篇:Postman 正確使用姿勢
