javasslhandshakeexception没有与ip地址匹配的主题可选名称

sqyvllje  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(565)

作为一个restful客户机,我可以使用postman软件成功地连接到服务器,而无需任何证书或安全设置(我从服务器收到正确的响应),但当我使用java程序调用它时,它会抛出以下异常:
javax.net.ssl.sslhandshakeexception:找不到与ip地址192.168.12.125匹配的主题替代名称
我也看到了这个没有解决我问题的链接。
下面是我使用的java代码:

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import java.io.Serializable;

public class CallService implements Serializable {
    private String uri = "https://192.168.12.125:443/ssdpn";    
    private Client client;
    private WebResource webResource;

    public void sendRequest(String input) {
        try {
            client = Client.create();
            webResource = client.resource(uri);

            String requestBody = prepareJSONFormatRequest(input);
            ClientResponse response =
                    webResource.path("/Service205")
                            .header("trackId", "1001")
                            .header("serviceId", "Service205")
                            .post(ClientResponse.class, requestBody);

            String result = response.getEntity(String.class);

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    private String prepareJSONFormatRequest(String input) {
        StringBuilder request = new StringBuilder();
        request.append("{ ").append("\"SerialNumber\":\"").append(input).append("\" }");
        return request.toString();
    }

}

在java程序中,我也不使用证书(就像在postman call中一样)。有人能帮我找出问题出在哪里吗?

eufgjt7s

eufgjt7s1#

我通过在构造函数中调用此方法进行了修复:

private void fixHttpsHandler() {
    try {

        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        }
        };

        SSLContext mySSLContext = SSLContext.getInstance("TLSv1.3");
        mySSLContext.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(mySSLContext.getSocketFactory());

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

然后

public class CallService implements Serializable {
    public CallService() {
            try {

                fixHttpsHandler();

            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
}

相关问题