gpt4 book ai didi

java - getInputStream 卡住并且永远不会完成

转载 作者:行者123 更新时间:2023-12-02 00:46:20 29 4
gpt4 key购买 nike

我正在使用 HttpURLConnection 从我的网站读取一个简单的文本文件,当它调用 getInputStream 时,它会卡住并且永远不会完成,getResponseCode 返回 200。它每次都首先工作,然后停止工作。

我在互联网上寻找解决方案,但没有任何效果。我认为这可能是网络服务器上的 ddos​​ 保护,或者是那里的某些东西阻止了它。

public static String getLatestInfo(String urlString){
URL url = null;
HttpURLConnection connection = null;
/*InputStream inputStream = null;
InputStreamReader isr = null;
BufferedReader in = null;*/
try {
url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
//connection.setRequestMethod("GET");
//connection.setDoOutput(true);
connection.setConnectTimeout(5000); // 5 seconds connectTimeout
connection.setReadTimeout(5000); // 5 seconds socketTimeout
connection.setRequestProperty("Connection", "close");
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestProperty("Accept", "text/xml");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

connection.connect();

if (connection.getResponseCode() == 200) {
try(InputStream inputStream = connection.getInputStream())
{
try(InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8")) {
try(BufferedReader in = new BufferedReader(isr))
{
String line;
String config = "";
while ((line = in.readLine()) != null) {
config = config + line + "\n";
}
return config;
}
}
}
/*inputStream = connection.getInputStream();
isr = new InputStreamReader(inputStream, "UTF-8");
in = new BufferedReader(isr);
String line;
String config = "";
while ((line = in.readLine()) != null) {
config = config + line + "\n";
}
return config;*/
}

}
catch (SocketTimeoutException e)
{
System.out.println("Timeout: " + e.getMessage());
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
try {
System.out.println(connection.getResponseCode());
} catch (IOException e1) {
e1.printStackTrace();
}
}
finally {
if (connection != null) connection.disconnect();
/*try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (in != null) in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (isr != null) isr.close();
} catch (IOException e) {
e.printStackTrace();
}*/
}
return null;}

我开始很简单,并添加了所有应该修复它的建议..它得到响应代码 200,然后卡住在 connection.getInputStream()

最佳答案

我的代码中有多个错误:

  1. 某些文件读取流未关闭。
  2. 我正在使用FileInputStream/FileOutputStream,它使它卡住。 This解释它。尽管它显示了解决方法,但它仍然会使其卡住。
  3. 我使用 SwingUtilities.invokeLater(new Runnable ()... 的主要问题是卡住和随机点。

解决了上述所有因素,解决了我的问题。

关于java - getInputStream 卡住并且永远不会完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57894232/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com