您的位置:首页 > 理论基础 > 计算机网络

OKHttp请求https证书验证

2018-03-15 15:18 447 查看
拿到srca.cer证书放入assets文件中

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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: