java - Java 请求中的 HTTPS SSL GET 失败

标签 java ssl

当我使用 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/

相关文章:

java - 无法使用类加载器建立连接

java - 在 Java 中使用相同的内部类名和对象名

htaccess 中附加域的 Wordpress SSL 问题

azure - 尝试为 Azure Web App 添加 SSL 绑定(bind)时没有证书

java - Spring Boot AsyncRestTemplate SSLSocketFactory

apache - 运行没有 http 的网站显示不同的内容

java - 为什么可以在 Kotlin 的类之外编写函数?

java - 如何显示两个维度数组中的值?

java - 我们是否应该在 JavaFX 自定义控件中使用 FXML?

iOS:调试通用链接