http请求No peer certificate的解决方法

不少同学在做HTTP请求新浪授权或新浪数据的时候会出现 javax.net.ssl.SSLPeerUnverifiedException: No peer certificate的异常。现给出解决方法(已通过测试)。

写了一个自定义类继承SSLSocketFactory:

  1. import java.io.IOException;
  2. import java.net.Socket;
  3. import java.net.UnknownHostException;
  4. import java.security.KeyManagementException;
  5. import java.security.KeyStore;
  6. import java.security.KeyStoreException;
  7. import java.security.NoSuchAlgorithmException;
  8. import java.security.UnrecoverableKeyException;
  9. import javax.net.ssl.SSLContext;
  10. import javax.net.ssl.TrustManager;
  11. import javax.net.ssl.X509TrustManager;
  12. import org.apache.http.conn.ssl.SSLSocketFactory;
  13. public class SSLSocketFactoryEx extends SSLSocketFactory {
  14. SSLContext sslContext = SSLContext.getInstance("TLS");
  15. public SSLSocketFactoryEx(KeyStore truststore)
  16. throws NoSuchAlgorithmException, KeyManagementException,
  17. KeyStoreException, UnrecoverableKeyException {
  18. super(truststore);
  19. TrustManager tm = new X509TrustManager() {
  20. public java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}
  21. @Override
  22. public void checkClientTrusted(
  23. java.security.cert.X509Certificate[] chain, String authType)
  24. throws java.security.cert.CertificateException {}
  25. @Override
  26. public void checkServerTrusted(
  27. java.security.cert.X509Certificate[] chain, String authType)
  28. throws java.security.cert.CertificateException {}
  29. };
  30. sslContext.init(null, new TrustManager[] { tm }, null);
  31. }
  32. @Override
  33. public Socket createSocket(Socket socket, String host, int
    port,boolean autoClose) throws IOException, UnknownHostException {
  34. return sslContext.getSocketFactory().createSocket(socket, host, port,autoClose);
  35. }
  36. @Override
  37. public Socket createSocket() throws IOException {
  38. return sslContext.getSocketFactory().createSocket();
  39. }
  40. }

复制代码

再来看看如何做回调:

  1. public static HttpClient getNewHttpClient() {
  2. try {
  3. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  4. trustStore.load(null, null);
  5. SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
  6. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  7. HttpParams params = new BasicHttpParams();
  8. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  9. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  10. SchemeRegistry registry = new SchemeRegistry();
  11. registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  12. registry.register(new Scheme("https", sf, 443));
  13. ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
  14. return new DefaultHttpClient(ccm, params);
  15. } catch (Exception e) {
  16. return new DefaultHttpClient();
  17. }
  18. }

复制代码

现在就可以拿这个HTTPClient去请求数据了!!!!!GOOD

 
上一篇:Python中的类(classes)


下一篇:sqlserver 删除表 视图 函数 存储过程