Ignorare i certificati SSL in Java e OkHttp3

Mattepuffo's logo
Ignorare i certificati SSL in Java e OkHttp3

Ignorare i certificati SSL in Java e OkHttp3

Oggi cercando di connettermi tramite Java ad un registratore di cassa usando OkHttp3 ottenevo questa eccezione:

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Il problema è di facile soluzione: bisogna fare in modo che la libreria ignori i certificati SSL.

Ecco un esempio:

package com.mp.test;

import okhttp3.*;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) {
        try {
            OkHttpClient client = clientWithoutSSL();

            MediaType mediaType = MediaType.parse("text/plain");
            RequestBody body = RequestBody.create(mediaType, "CLEARnRESPRNtttttttttttt;Annulla eventuali transazioni apertenCHIAVE REGnvend rep=1, prezzo=1nchiusnwecfinen");
            Request request = new Request.Builder()
                    .url("https://192.168.1.120/cmd/wec")
                    .method("POST", body)
                    .addHeader("Content-Type", "text/plain")
                    .build();
            Response response = client.newCall(request).execute();
            System.out.println(response);
        } catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {
            System.out.println(e.getMessage());
        }
    }

    private static OkHttpClient clientWithoutSSL() throws KeyManagementException, NoSuchAlgorithmException {
        final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[]{};
                    }
                }
        };

        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        builder.hostnameVerifier((hostname, session) -> true);

        OkHttpClient okHttpClient = builder
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .build();

        return okHttpClient;
    }

}

Enjoy!


Share this Post

Commentami!