'java.net.SocketTimeoutException:connect timed out'
我在循环一段时间后得到这个错误。
为什么我得到SocketTimeoutException?我怎么能解决这个错误?
@Override
public void run() {
while (true) {
try {
URLConnection connection = getURLConnection("http://www.trekpv.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println(s);
}
reader.close();
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private URLConnection getURLConnection(String s) throws IOException {
URL url = new URL(s);
URLConnection urlconnection = url.openConnection();
urlconnection.setConnectTimeout(10000);
urlconnection.setReadTimeout(10000);
urlconnection.addRequestProperty("Connection", "keep-alive");
urlconnection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120716 Firefox/15.0a2");
urlconnection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
urlconnection.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
urlconnection.addRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
return urlconnection;
}
答案 0 :(得分:1)
在指定的url未在特定持续时间内获取时发生SocketTimeoutException。这可能是因为互联网连接速度缓慢,或者代码中存在一些错误导致无法getURLConnection("http://www.trekpv.com")
功能获取网址。
答案 1 :(得分:0)
'连接超时'表示根本没有响应。可能会有防火墙。