HttpClient和OkHttp關于Https請求問題

pangyanming 8年前發布 | 91K 次閱讀 Android開發 移動開發

來自: http://blog.csdn.net//guijiaoba/article/details/45490479


項目中遇到登錄接口,使用的時https接口,所以客戶端必須要進行配置,原先的項目使用的時Apache的Httpclient,Android的api接口也內置了httpclient,但是Android系統在4.x以后不建議使用了Httpclient,推薦使用urlconnection,但是urlconnection畢竟太過于原始,所以我選擇了okhttp作為http請求庫。

OKhttp的地址

由于服務器使用的是通用的https加密,所以我在這里只是介紹通用的加密方式。

Httpclient

    static class SSLSocketFactoryEx extends SSLSocketFactory {

    SSLContext sslContext = SSLContext.getInstance("TLS");

    public SSLSocketFactoryEx(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[]{tm}, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}



static HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactoryEx sf = new SSLSocketFactoryEx(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();
    }
}</pre> 

OkHttp

    static class HttpStackPlus extends HurlStack {
        private final OkUrlFactory mFactory;

    public HttpStackPlus() {
        this(new OkHttpClient());
    }

    public HttpStackPlus(OkHttpClient client) {
        if (client == null) {
            throw new NullPointerException("Client must not be null.");
        } else {
            try {
                TrustManager tm = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };

                SSLContext e = SSLContext.getInstance("TLS");

                e.init(null, new TrustManager[]{tm}, null);

                client.setSslSocketFactory(e.getSocketFactory());

            } catch (Exception e) {
                throw new AssertionError();
            }

            this.mFactory = new OkUrlFactory(client);
        }
    }

    protected HttpURLConnection createConnection(URL url) throws IOException {
        return this.mFactory.open(url);
    }
}

public static RequestQueue newRequestQueue(Context context) {
    return Volley.newRequestQueue(context, new HttpStackPlus());
}</pre> </div>

 本文由用戶 pangyanming 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!