在我的机器上(在主方法上)我可以使用此代码使用https网络服务:
URL url;
HttpsURLConnection connection;
HttpsURLConnection.setDefaultHostnameVerifier(
new javax.net.ssl.HostnameVerifier(){
public boolean verify(String hostname,
javax.net.ssl.SSLSession sslSession) {
return true;
}
});
//prepare the request
byte[] postData = xml.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
url = new URL(ENDPOINT_URL);//https endpoint
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(postData);
//make the request and get response xml string
connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
请注意,在代码中我绕过了主机名验证,根据这篇文章的答案:Java SSLException: hostname in certificate didn't match
但是,如果我尝试使用完全相同的https Web服务,使用完全相同的代码,在完全相同的机器(我的本地机器)上,但是从Tomcat 8上部署的webapp,我得到错误:
Caused by: javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: No name matching localhost found
我已经搜索了这个问题的解决方案和解决方案,但没有找到。我很无能为力。你知道为什么会这样吗?