1

如何以及在哪里实现 setReadTimeout 或 setConnectTimeout?我下面的测试总是在编译之前给我抛出错误未定义

当没有连接时,它会在 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) {
}

感谢您的帮助

克里斯

4

1 回答 1

1

使用 URL 连接。

 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();

这对我有用。由于您的评论克里斯蒂安穆勒,我在几个网站上进行了尝试并调整了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>
于 2013-09-12T14:07:06.627 回答