//封装OkhttpManager
package com.twd.ttt;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collection;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.x500.X500Principal;
import okhttp3.OkHttpClient;
/**
* Created by twd on 2017/12/21.
*/
public class OkhttpManager {
static private OkhttpManager mOkhttpManager=null;
private InputStream mTrustrCertificate;
static public OkhttpManager getInstance()
{
if(mOkhttpManager==null)
{
mOkhttpManager=new OkhttpManager();
}
return mOkhttpManager;
}
private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream in = null; // By convention, 'null' creates an empty key store.
keyStore.load(in, password);
return keyStore;
} catch (IOException e) {
throw new AssertionError(e);
}
}
private X509TrustManager trustManagerForCertificates(InputStream in)
throws GeneralSecurityException {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
// Put the certificates a key store.
char[] password = "password".toCharArray(); // Any password will work.
KeyStore keyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = Integer.toString(index++);
keyStore.setCertificateEntry(certificateAlias, certificate);
}
// Use it to build an X509 trust manager.
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
return (X509TrustManager) trustManagers[0];
}
public void setTrustrCertificates(InputStream in)
{
mTrustrCertificate=in;
}
public InputStream getTrustrCertificates()
{
return mTrustrCertificate;
}
public OkHttpClient build()
{
OkHttpClient okHttpClient=null;
if(getTrustrCertificates()!=null)
{
X509TrustManager trustManager;
SSLSocketFactory sslSocketFactory;
try {
trustManager = trustManagerForCertificates(getTrustrCertificates());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManager }, null);
sslSocketFactory = sslContext.getSocketFactory();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
okHttpClient=new OkHttpClient.Builder()
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
try {
String peerHost = session.getPeerHost(); //服务器返回的主机名
String str_new = "twd";//验证证书
X509Certificate[] peerCertificates = (X509Certificate[]) session.getPeerCertificates();
for (X509Certificate certificate : peerCertificates) {
X500Principal subjectX500Principal = certificate
.getSubjectX500Principal();
String name = subjectX500Principal.getName();
String[] split = name.split(",");
for (String str : split) {
if (str.startsWith("CN")) {//证书绑定的域名或者ip
if (str.contains(str_new)) {
return true;
}
}
}
}
} catch (SSLPeerUnverifiedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return false;
}
})
.sslSocketFactory(sslSocketFactory, trustManager)
.build();
}
else
{
okHttpClient=new OkHttpClient.Builder()
.build();
}
return okHttpClient;
}
}
//请求代码
OkhttpManager.getInstance().setTrustrCertificates(getAssets().open("证书名.cer"));//放到Assets下或者只要能访问的地方
OkHttpClient mOkhttpClient= OkhttpManager.getInstance().build();
MediaType JSON = MediaType.parse("application/text; charset=utf-8");
RequestBody body = RequestBody.create(JSON, "参数");
Request request = new Request.Builder().url("https://192.168.1.178:8443/test.json").post(body).build();
Call call = mOkhttpClient.newCall(request);
Response response =call.execute();
String str =response.body().string();