拿到srca.cer证书放入assets文件中
参考原文@我们不生产代码, 只是Bug 的搬运工
private static SSLSocketFactory sslSocketFactory = null;
public static void getSocketFactory() {
try {
InputStream certificate = MyApplication.mContext.getAssets().open("srca.cer");
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
int index = 0;
String certificateAlias = Integer.toString(index++);
keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
try {
if (certificate != null) {
certificate.close();
}
} catch (IOException e) {
e.printStackTrace();
}
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
sslContext.init( null, trustManagerFactory.getTrustManagers(), new SecureRandom() );
sslSocketFactory = sslContext.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
/*** get请求**/
public void sendGetRepuest(String url, final CallBacks callbacks) {
final Request request = new Request.Builder().url(url).build();
client.newBuilder()
.connectTimeout(timeOut, TimeUnit.SECONDS)
.readTimeout(timeOut, TimeUnit.SECONDS)
.writeTimeout(timeOut, TimeUnit.SECONDS)
.sslSocketFactory(sslSocketFactory)//设置sslSocketFactory
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
callbacks.onError(e.toString());
}
//解析成功
@Override public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()) {
callbacks.onSuccess(response.body().string());
} else {
callbacks.onError(response.toString());
}
}
});
}
public class MyApplication extends Application {
public static Context mContext = null;
@Override public void onCreate() {
super.onCreate();
mContext = this;
OkHttpUtils.getSocketFactory();
}
}
作者的闲章野笔