Android开发笔记

Android OkHttp3 访问自签名https服务

2018-05-25  本文已影响1211人  小杨哥

引:在开发中经常遇到自己签名的本地服务,在android开发时报错

 javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

1.创建工具类HttpsTrustManager

package com.tuanshang.p2pdemo.utils;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpsTrustManager implements X509TrustManager
{
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

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

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }


    public static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory sSLSocketFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new HttpsTrustManager()},
                    new SecureRandom());
            sSLSocketFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return sSLSocketFactory;
    }


    public   static  class  TrustAllHostnameVerifier implements  HostnameVerifier
    {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
         return   true;
        }
    }
}

2.调用方法

 OkHttpClient client = new OkHttpClient();
        OkHttpClient  mOkHttpClient = client.newBuilder()

                .sslSocketFactory(HttpsTrustManager.createSSLSocketFactory())
                .hostnameVerifier(new HttpsTrustManager.TrustAllHostnameVerifier())
                .build();

        RequestBody formBody = new FormBody.Builder()
                .add("page", page + "")
                .add("pagesize", "10")
                .build();
        Request request = new Request.Builder().url(UrlsUtils.ZJLCstring + UrlsUtils.ZJLCBorrow_list).post(formBody).build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure",e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String data = response.body().string();
                
                        }
                    }
                });
            }
        });
    }
上一篇下一篇

猜你喜欢

热点阅读