我正在使用HttpURLConnection从我的网站中读取一个简单的文本文件,当它调用getInputStream时,它冻结并且从未完成,getResponseCode返回200。它每次都在工作,然后停止工作。
我在整个互联网上都在寻找解决方案,但没有任何解决方法。我认为这可能是Web服务器上的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()
答案 0 :(得分:0)
我的代码中有很多错误:
FileInputStream/FileOutputStream
,它正在冻结。 This对此进行了解释。尽管它可以解决问题,但仍会使其冻结。SwingUtilities.invokeLater(new Runnable ()...
的主要问题是冻结和随机点。解决以上所有问题,就解决了我的问题。