通過HttpClient呼叫介面時忽略SSL證書驗證
在專案過程中發現呼叫的介面地址為https形式的,一般用httpclient呼叫會丟擲異常:Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated,經過查詢資料發現時因為https會使用SSL數字證書驗證,而服務端並沒有提供相應的SSL數字證書,這就需要在呼叫時繞過校驗,具體實現程式碼如下:
1.httpclient
public static void main(String[] args) throws HttpException, IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient = wrapClient(httpclient);
HttpPost httppost = new HttpPost(url);
StringEntity myEntity = new StringEntity(test(), "utf-8");
httppost.addHeader("Content-Type", "text/html;charset=utf-8");
httppost.setEntity(myEntity);
httppost.addHeader("Authorization","Bearer YWMtlZKThgG9EeSdfPG0cx2i0wAAAUcaGn61pdZR1lx5O8fYo0H8cwINV1NFExI");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
InputStreamReader reader = new InputStreamReader(resEntity.getContent(), "utf-8");
char[] buff = new char[1024];
int length = 0;
while ((length = reader.read(buff)) != -1) {
System.out.println(new String(buff, 0, length));
}
httpclient.getConnectionManager().shutdown();
}
2.取消校驗SSL
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) {
}
public void checkServerTrusted(X509Certificate[] xcs,
String string) {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
X509HostnameVerifier hv = new X509HostnameVerifier(){
@Override
public boolean verify(String hostname, SSLSession session) {
// TODO Auto-generated method stub
return true;
}
@Override
public void verify(String arg0, SSLSocket arg1) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void verify(String arg0, X509Certificate arg1)
throws SSLException {
// TODO Auto-generated method stub
}
@Override
public void verify(String arg0, String[] arg1, String[] arg2)
throws SSLException {
// TODO Auto-generated method stub
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,(X509HostnameVerifier) hv);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
return new DefaultHttpClient(ccm, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
3.需要的jar包為httpclient涉及的jar包