gpt4 book ai didi

Java setReadTimeout() 不起作用

转载 作者:行者123 更新时间:2023-11-30 03:22:59 25 4
gpt4 key购买 nike

如何以及在何处实现 setReadTimeout 或 setConnectTimeout?我的下面的测试总是在编译之前抛出错误 its undefined

当没有连接时,它会在 in.readLine() 处阻塞,应用程序将永远等待

try {
URL url = new URL("http://mydomain/myfile.php");

//url.setReadTimeout(5000); does not work

InputStreamReader testi= new InputStreamReader(url.openStream());
BufferedReader in = new BufferedReader(testi);

//in.setReadTimeout(5000); does not work

stri = in.readLine();
Log.v ("GotThat: ",stri);
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

谢谢你的帮助

克里斯

最佳答案

使用 URLConnection。

 URL url = new URL("http://mydomain/myfile.php");
URLConnection connection = url.openConnection()
int timeoutMs = 2000;
connection.setReadTimeout(timeoutMs );

InputStream urlInputStream = connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(urlInputStream));

String firstLine = in.readLine();
System.out.println("GotThat: " + firstLine);
in.close();

这对我有用。由于您的评论 christian Muller,我在几个网站上进行了尝试并调整了 timeoutMs 值。将 timeoutMs 设置为 250 毫秒应该会导致 SocketTimeoutException。如果你然后逐步增加它,你会看到最后你读了一行。

例如,如果我尝试:

URL url = new URL("http://msdn.microsoft.com/en-US/");
URLConnection connection = url.openConnection();
int timeoutMs = 250;
connection.setReadTimeout(timeoutMs);

我明白了

Exception in thread "main" java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:695)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:640)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1195)
at test.Main.main(Main.java:25)

如果我对 550 timeoutMs 进行同样的尝试,它会起作用:

 GotThat: <!DOCTYPE html>

关于Java setReadTimeout() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18766443/

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