HTTPS使用安全证书,OkHttpClient实现
开发中调用其他平台的服务代码,需要使用https请求数据,网上搜索了好多,多半是绕过认证,这个是加载证书的,可以访问使用,记录下来备用。
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManagerFactory; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import org.apache.commons.lang.StringUtils; import com.alibaba.fastjson.util.IOUtils; public class OkHttpTool { public static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8"); public static final String AUTH_FILE_URL = "AUTH_FILE_URL";//配置的地址 public static String post(String url, String json, String token) { String result = ""; InputStream caInput =null; Response response =null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); caInput = new BufferedInputStream(new FileInputStream(AUTH_FILE_URL)); Certificate ca = cf.generateCertificate(caInput); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); RequestBody body = RequestBody.create(JSON_TYPE, json); Request request = new Request.Builder().url(url).post(body) .addHeader("clientId", "204") .addHeader("Client-Type", "android") .addHeader("Client-Version", "2.2.6") .addHeader("plain-text-transfer", "true") .addHeader("token", StringUtils.isBlank(token) ? "" : token).build(); OkHttpClient client = new OkHttpClient.Builder() .sslSocketFactory(context.getSocketFactory()) .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .hostnameVerifier(new TrustAnyHostnameVerifier()) .build(); response = client.newCall(request).execute(); if (response.isSuccessful()) { result = response.body().string(); } else { throw new IOException("Unexpected code " + response); } caInput.close(); response.close(); } catch (Exception e) { e.printStackTrace(); }finally{ if(caInput!=null){ IOUtils.close(caInput); } if(response!=null){ IOUtils.close(response); } } return result; } private static class TrustAnyHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; } } }