作为一个安静的客户端,我可以使用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调用中所做的那样)。 谁能帮我找出问题出在哪里?
我通过在构造函数中调用此方法来修复:
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());
}
}
}
这是完美的解决方案,我试图使用 IP 地址调用 API,然后遇到了这个问题“java SSLHandshakeException No subject Alternative名称匹配 IP 地址”。
使用此代码,我可以使用 IP 调用 API。
谢谢您的解决方案。