gpt4 book ai didi

java - 抛出 SocketTimeoutException

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:45 29 4
gpt4 key购买 nike

'java.net.SocketTimeoutException:连接超时'
循环一段时间后我收到此错误。为什么我会收到 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;
}

最佳答案

当指定的 url 在一定时间内未获取时,会发生 SocketTimeoutException。出现这种情况的原因可能是互联网连接速度较慢,或者代码中存在某些错误,导致 getURLConnection("http://www.trekpv.com") 函数无法获取 URL。

关于java - 抛出 SocketTimeoutException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21080449/

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