无法从HTTPS URL获取Inputsream-连接超时(ConnectException)

时间:2019-06-06 11:48:17

标签: java inputstream connect

我打算编写一种下载图像的方法。到目前为止,所有实现都失败了,因此我将其归结为产生错误的代码,并删除了其他所有内容,因此该代码仅显示了重要部分。关键是:当我使用HTTPS URL时,getinputstream()方法会导致连接错误。我该如何规避?可能是因为证书吗?令我惊讶的是,我在C#中使用了类似的代码,但是Java需要绕过HTTPS连接的证书吗?

public static void img_DL(String s) throws IOException {

URL url = new URL(s);
InputStream inputStream;
String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
URLConnection con = url.openConnection();
con.setRequestProperty("User-Agent", USER_AGENT);
inputStream = con.getInputStream();
inputStream.close();
}

这里是堆栈跟踪:

Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at application.Img.img_DL(Img.java:48)
at application.FXMLController.download_img(FXMLController.java:215)
... 58 more

1 个答案:

答案 0 :(得分:0)

  1. 您可以检查异常的详细信息。
  2. 通过设置-Djavax.net.debug = all来运行以调试错误。看到 Debugging SSL/TLS Connections
  3. 如果发生超时,请检查超时设置。您可以通过设置系统属性来增加超时时间。

    System.setProperty(“ sun.net.client.defaultConnectTimeout”,“ 10000”);