Created
March 13, 2017 13:57
-
-
Save rybalkinsd/940a35ccefb9849c887ccf32d3be744b to your computer and use it in GitHub Desktop.
OkHttp + self signed cert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.aliexpress.international.http.client; | |
import okhttp3.*; | |
import org.junit.Test; | |
import javax.net.ssl.*; | |
import java.io.BufferedInputStream; | |
import java.io.InputStream; | |
import java.security.KeyStore; | |
import java.security.cert.Certificate; | |
import java.security.cert.CertificateFactory; | |
import java.util.concurrent.TimeUnit; | |
public class HttpClientTest { | |
private static final String HOST = ""; | |
@Test | |
public void okHttpTest() throws Exception { | |
SSLContext sslContext; | |
TrustManager[] trustManagers; | |
try { | |
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); | |
keyStore.load(null, null); | |
InputStream certInputStream = getClass().getResourceAsStream("/my-server.crt"); | |
BufferedInputStream bis = new BufferedInputStream(certInputStream); | |
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); | |
while (bis.available() > 0) { | |
Certificate cert = certificateFactory.generateCertificate(bis); | |
keyStore.setCertificateEntry(, cert); | |
} | |
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); | |
trustManagerFactory.init(keyStore); | |
trustManagers = trustManagerFactory.getTrustManagers(); | |
sslContext = SSLContext.getInstance("TLS"); | |
sslContext.init(null, trustManagers, null); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return; | |
} | |
OkHttpClient client = new OkHttpClient.Builder() | |
.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) | |
.hostnameVerifier((s, sslSession) -> | |
HOST.equals(s) | |
) | |
.readTimeout(5, TimeUnit.SECUNDS) | |
.build(); | |
Request request = new Request.Builder() | |
.url(PROTOCOL+ "://" + HOST + ":" + PATH) | |
.post(RequestBody.create(MediaType.parse("application/json"), "{ \"data\": \"value\"} ")) | |
.build(); | |
Response response = client.newCall(request).execute(); | |
System.out.println(response.body().string()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment