java自定义证书,向OkHttp客户端添加自定义证书

I am trying to make Android app, where I can get and parse HTML (from site which doesnt have API). I am using OkHttp. The site has untrusted (but valid) certificate. I am getting:

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

I've already set up the official way (https://developer.android.com/training/articles/security-ssl#java) and now I need to link it with OkHttpClient.

I tried

OkHttpClient client = new OkHttpClient;

OkHttpClient.Builder builder = client.newBuilder();

builder.sslSocketFactory(sslcontext.getSocketFactory()).build();

But it doesnt work, and also it is deprecated.

Thanks

解决方案

Only use for debugging. Using this code means trusting any certificate which is as good as not using https at all.

You need to use sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager) which is not deprecated.

Use this variable (which creates a trust manager that does not validate certificate chains):

TrustManager[] trustAllCerts = new TrustManager[] {

new X509TrustManager() {

@Override

public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {

}

@Override

public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {

}

@Override

public java.security.cert.X509Certificate[] getAcceptedIssuers() {

return new java.security.cert.X509Certificate[]{};

}

}

};

and pass to sslSocketFactory() in this way:

builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);

also apply this to verify every host:

builder.hostnameVerifier(new HostnameVerifier() {

@Override

public boolean verify(String hostname, SSLSession session) {

return true;

}

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值