public void run() throws Exception { String localhost = InetAddress.getByName("localhost").getCanonicalHostName(); HeldCertificate localhostCertificate = new HeldCertificate.Builder() .addSubjectAlternativeName(localhost) .build(); HandshakeCertificates serverCertificates = new HandshakeCertificates.Builder() .heldCertificate(localhostCertificate) .build(); MockWebServer server = new MockWebServer(); server.useHttps(serverCertificates.sslSocketFactory(), false); server.enqueue(new MockResponse()); HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder() .addTrustedCertificate(localhostCertificate.certificate()) .build(); OkHttpClient client = new OkHttpClient.Builder() .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager()) .build(); Call call = client.newCall(new Request.Builder() .url(server.url("/")) .build()); Response response = call.execute(); System.out.println(response.handshake().tlsVersion()); }
/** Returns an SSL client for this host's localhost address. */ public static synchronized HandshakeCertificates localhost() { if (localhost != null) return localhost; try { // Generate a self-signed cert for the server to serve and the client to trust. HeldCertificate heldCertificate = new HeldCertificate.Builder() .commonName("localhost") .addSubjectAlternativeName(InetAddress.getByName("localhost").getCanonicalHostName()) .build(); localhost = new HandshakeCertificates.Builder() .heldCertificate(heldCertificate) .addTrustedCertificate(heldCertificate.certificate()) .build(); return localhost; } catch (UnknownHostException e) { throw new RuntimeException(e); } }
/** Returns an SSL client for this host's localhost address. */ public static synchronized HandshakeCertificates localhost() { if (localhost != null) return localhost; try { // Generate a self-signed cert for the server to serve and the client to trust. HeldCertificate heldCertificate = new HeldCertificate.Builder() .commonName("localhost") .addSubjectAlternativeName(InetAddress.getByName("localhost").getCanonicalHostName()) .build(); localhost = new HandshakeCertificates.Builder() .heldCertificate(heldCertificate) .addTrustedCertificate(heldCertificate.certificate()) .build(); return localhost; } catch (UnknownHostException e) { throw new RuntimeException(e); } }