当我使用 http 协议(protocol)请求某些内容时,我的代码可以正常工作并且我得到了预期的响应。但是当我创建一个使用 https 的版本时,我收到了 SSL 错误。我已经按照 this question 中的步骤进行操作,而且我认为我不需要 this question 中描述的 key /信任管理器.请参阅下面的代码。我将 key 和 trustmanager 设置为 null,因此 java 将采用默认值。我在那一步似乎没有出错,错误发生在 inputStream = connection.getInputStream();
行。我不知道我还需要添加/设置什么来设置安全连接?
private String runSecureService(URL url)
{
HttpsURLConnection connection = null;
InputStream inputStream = null;
SSLContext sslContext = null;
try
{
sslContext = SSLContext.getInstance("SSL");
}
catch (NoSuchAlgorithmException e)
{
//this exception doesn't occur
}
try
{
sslContext.init(null, null, null);
}
catch (KeyManagementException e)
{
//this exception doesn't occur
}
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
try
{
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", clientCredentials.getBase64Authentication());
!-----> inputStream = connection.getInputStream(); <------!
InputStreamReader responseReader = new InputStreamReader(inputStream);
//Read, print and return the response.
...
return response;
}
catch (IOException e)
{
//do stuff...
}
finally
{
//close connection and inputstream...
}
}
这里是错误:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at sun.security.ssl.InputRecord.handleUnknownRecord(Unknown Source)
at sun.security.ssl.InputRecord.read(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
最佳答案
如果您尝试发出 HTTPS 请求,但连接到远程服务器上的 HTTP 端口,则会收到此消息。
可能是您在请求中使用了错误的 HTTPS 端口号……或者服务器配置错误并且在 应该 的 HTTPS 端口上有一个 HTTP 连接监听器。
关于java - Java 请求中的 HTTPS SSL GET 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21756419/