因为sslSocketFactory(javax.net.ssl.sslSocketFactory('已弃用,我应该使用什么?谢谢。。。已弃用。SSLSocketFactory不公开其X509TrustManager,这是OkHttp构建干净证书链所需的字段。相反,此方法必须使用反射来提取信任管理器。应用程序应该更喜欢调用sslSocketFactory(sslSocketFactory,X509TrustManager(,这样可以避免这种反射。设置用于保护HTTPS连接的套接字工厂。如果未设置,将使用系统默认值。
try {
client = new OkHttpClient().newBuilder()
.sslSocketFactory(trustCert().getSocketFactory())
.build();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new FormBody.Builder()
.build();
Request request = new Request.Builder()
.url("https://example.com")
.method("GET", null)
.addHeader("auth-token", token)
.addHeader("Authorization", "Bearer"+" "+token)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
odgovor = response.body().string();
System.out.println(odgovor);
} catch (IOException e) {
e.printStackTrace();
}
private SSLContext trustCert() throws CertificateException,IOException, KeyStoreException,
NoSuchAlgorithmException, KeyManagementException {
AssetManager assetManager = getAssets();
InputStream is = getApplicationContext().getResources().openRawResource(R.raw.gdig2);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca = cf.generateCertificate(is);
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
return context;
}
Use,#sslSocketFactory(sslSocketFactory,X509TrustManager(
client=new okHttpClient((.newBuilder((.sslSocketFactory(trustCert((.getSocketFactory((,(X509TrustManager(tmf.trustManagers.get(0((;