我创建了2个类: - 这个扩展OkHttp并有一个新方法getUnsafeOkHttpClient()。
public class GetExampleOkHttp extends OkHttpClient {
public OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final 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[] {};
}
} };
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
和其他主要课程:
class ExampleOkHttpMain
public static void main(String[] args) throws IOException {
GetExampleOkHttp example = new GetExampleOkHttp();
example.getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url("https://lachuzhnikov.kiev.ua/test.txt")
.build();
Response response = example.newCall(request).execute();
System.out.println(response.body().string());
}
}
但我仍有错误:
线程“main”中的异常javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:PKIX路径构建失败: sun.security.provider.certpath.SunCertPathBuilderException:无法 找到所请求目标的有效证书路径 在sun.security.ssl.Alerts.getSSLException(未知来源) at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source) 在sun.security.ssl.Handshaker.fatalSE(未知来源)
答案 0 :(得分:0)
1:下载https://sourceforge.net/projects/portecle/
2:打开firefox并转到页面并导出cer
3:备份Java \ jdk .... \ jre \ lib \ security \ cacerts(例如:C:\ Program Files \ Java \ jdk1.7.0_79 \ jre \ lib \ security)
4:将cacerts复制到另一个文件夹
5:Portecle在步骤2中打开文件cacerts(pass:changeit)import cer并保存
6:复制并替换新的cacerts Java \ jdk .... \ jre \ lib \ security \ cacerts