Skip to content

Instantly share code, notes, and snippets.

@wildone
Created September 6, 2023 02:06
Show Gist options
  • Save wildone/d3aee880d1ffe4ca8b7378665f9c31f2 to your computer and use it in GitHub Desktop.
Save wildone/d3aee880d1ffe4ca8b7378665f9c31f2 to your computer and use it in GitHub Desktop.
POST a JSON to a URL with insecure or invalid SSL certs using latest JDK 11 HttpClient
```java
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
try {
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Creat HttpClient with new SSLContext.
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofMillis(3 * 1000))
.sslContext(sc) // SSL context 'sc' initialised as earlier
.build();
// Create request.
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(<URL>))
.timeout(Duration.ofMinutes(1))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(<PAYLOAD JSON STRING>))
.build();
//Send Request
HttpResponse<String> response =
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
//Access response JSON
String responseJson = response.body();
} catch (Exception e) {
throw new Exception(e);
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment