Java请求中的HTTPS SSL GET失败

时间:2014-02-13 14:03:16

标签: java ssl

当我使用http协议请求某些内容时,我的代码可以工作,我得到了预期的响应。但是当我创建一个与https一起使用的版本时,我收到了一个SSL错误。我已经按照this question中的步骤操作了,我认为我不需要this question中所述的密钥/信任管理器。请参阅下面的代码。我将key和trustmanager设置为null,因此java将采用默认值。我似乎没有在该步骤上收到错误,错误发生在inputStream = connection.getInputStream();行上。我不知道还需要添加/设置什么来设置scure连接?

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)

1 个答案:

答案 0 :(得分:1)

如果您尝试发出HTTPS请求,但是连接到远程服务器上的HTTP端口,则可以收到此消息。

您可能在请求中使用了错误的HTTPS端口号...或者服务器配置错误,并且 应该是HTTPS端口的HTTP连接侦听器。< / p>