HttpClient 如何忽略证书验证访问https - ALLOW_ALL_HOSTNAME_VERIFIER(二)
/** * @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.忽略证书验证
DefaultHttpClient httpclient = (DefaultHttpClient) getNewHttpClient(); HttpGet httpGet = new HttpGet(httpGetUrl); CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("domainName", ".hub.com"); cookie.setVersion(0); cookie.setDomain(".hub.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); // Create local HTTP context HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); /////////////////////////////add cookie - END try { //HttpResponse response = httpclient.execute(httpGet); HttpResponse response = httpclient.execute(httpGet, localContext); }catch (Exception e) {}
附上not-yet-commons-ssl-0.3.11.jar