HttpClient 如何忽略证书验证访问HTTPS接口,解决步骤如下:
1. 设置可以访问HTTPS
- /**
- * @Title: getNewHttpClient
- * @Description: Methods Description
- * @param @return
- * @return HttpClient
- * @throws
- */
- private HttpClient getNewHttpClient() {
- try {
- KeyStore trustStore = KeyStore.getInstance(KeyStore
- .getDefaultType());
- trustStore.load(null, null);
- SSLSocketFactory sf = new SSLSocketFactory(trustStore);
- sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
- HttpParams params = new BasicHttpParams();
- HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
- HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
- SchemeRegistry registry = new SchemeRegistry();
- registry.register(new Scheme(“http”, PlainSocketFactory
- .getSocketFactory(), 80));
- registry.register(new Scheme(“https”, sf, 443));
- ClientConnectionManager ccm = new ThreadSafeClientConnManager(
- params, registry);
- return new DefaultHttpClient(ccm, params);
- } catch (Exception e) {
- return new DefaultHttpClient();
- }
- }
2. 忽略证书验证,使用HttpClient访问HTTPS接口
- DefaultHttpClient httpclient = (DefaultHttpClient) getNewHttpClient();
- try {
- //Secure Protocol implementation.
- SSLContext ctx = SSLContext.getInstance(”SSL”);
- //Implementation of a trust manager for X509 certificates
- X509TrustManager tm = new X509TrustManager() {
- public void checkClientTrusted(X509Certificate[] xcs,
- String string) throws CertificateException {
- }
- public void checkServerTrusted(X509Certificate[] xcs,
- String string) throws CertificateException {
- }
- public X509Certificate[] getAcceptedIssuers() {
- return null;
- }
- };
- ctx.init(null, new TrustManager[] { tm }, null);
- SSLSocketFactory ssf = new SSLSocketFactory(ctx);
- ClientConnectionManager ccm = httpclient.getConnectionManager();
- //register https protocol in httpclient’s scheme registry
- SchemeRegistry sr = ccm.getSchemeRegistry();
- sr.register(new Scheme(“https”, 443, ssf));
- } catch (Exception e) {
- e.printStackTrace();
- }
- HttpGet httpGet = new HttpGet(httpGetUrl);
- HttpResponse response = httpclient.execute(httpGet, localContext);