2019独角兽企业重金招聘Python工程师标准>>>
http请求No peer certificate的解决方法
但是里面提出的解决方案都是针对自己实现HttpClient或者HttpURLConnection的,而我是使用了Google官方提供的Volley,如果要修改源码的话比较麻烦。于是我大胆猜测Volley底层是采用HttpURLConnection实现的,可以在进行StringRequest之前设置一个X509TrustManager。
首先新建一个类FakeX509TrustManager:
public class FakeX509TrustManager implements X509TrustManager { private static TrustManager[] trustManagers; private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {}; @Override public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { //To change body of implemented methods use File | Settings | File Templates. } public boolean isClientTrusted(X509Certificate[] chain) { return true; } public boolean isServerTrusted(X509Certificate[] chain) { return true; } @Override public X509Certificate[] getAcceptedIssuers() { return _AcceptedIssuers; } public static void allowAllSSL() { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { // TODO Auto-generated method stub return true; } }); SSLContext context = null; if (trustManagers == null) { trustManagers = new TrustManager[] { new FakeX509TrustManager() }; } try { context = SSLContext.getInstance("TLS"); context.init(null, trustManagers, new SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); } }
然后在进行StringRequest之前设置:
FakeX509TrustManager.allowAllSSL(); mStringRequest = new StringRequest(Request.Method.POST, url, getDefaultSuccessListener(), mErrorListener){ @Override protected MapgetParams() throws AuthFailureError { return params; } }; mRequestQueue.add(mStringRequest);
再次运行则发现可以正常获取数据。