当我请求使用http协议的东西时,我的代码工作,我得到了预期的响应。但是当我创建一个版本来使用https时,我会收到SSL错误。我已经按照this question中的步骤操作,并且我认为我不需要this question中描述的密钥/信任管理员。请参阅下面的代码。我将key和trustmanager设置为null,以便java将采用默认值。我似乎没有得到该步骤的错误,错误发生在行inputStream = connection.getInputStream();
。我不知道还需要添加/设置什么来设置scure连接?HTTPS SSL GET在java请求失败
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)
你试图在哪个端口进行通信?你确定你正在使用SSL端口吗? – DanielBarbarian
只需指出你正在用'sslContext.init(null,null,null)'做什么''基本上是创建一个用默认值初始化的'SSLContext',然后从它获得一个'SSLSocketSocketFactory',然后将其设置为您的'HttpsURLConnection'上的默认'SSLSocketFactory'。使用默认值更改默认值都是没有意义的(除非您之前在其他地方更改过)。 – Bruno
我不知道,我认为你总是有一个指定一个sslContext,即使它是一个默认的。如果我正确地解释你在说什么,我可以放弃这些代码行,结果会一样吗? – user1884155