Accept server's self-signed ssl certificate in Java client
To accept a server's self-signed SSL certificate in a Java client, you can create a custom javax.net.ssl.X509TrustManager
and use it to override the default trust manager. The custom trust manager will trust all SSL certificates, including self-signed ones.
Here is an example of how you can create a custom trust manager to accept a server's self-signed SSL certificate in a Java client:
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class CustomTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
// Trust all clients
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
// Trust all servers
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// Return empty array of certificates
return new X509Certificate[0];
}
}
This code defines a custom trust manager, CustomTrustManager
, that trusts all SSL certificates by overriding the checkClientTrusted()
and checkServerTrusted()
methods.
To use the custom trust manager, you will need to create an SSLContext
and set the trust manager using the init()
method. Here is an example of how you can create an SSLContext
and use the custom trust manager:
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class Main {
public static void main(String[] args) throws Exception {
// Create an SSL context with the custom trust manager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { new CustomTrustManager() }, null);
// Create an SSL connection socket factory with the SSL context
SSLConnectionSocketFactory socket