Java setReadTimeout()不起作用

时间:2013-09-12 14:03:48

标签: java android sockets

如何以及在何处实现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) {
}

感谢您的帮助

克里斯

1 个答案:

答案 0 :(得分:1)

使用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>