在下面如何以及在何处实现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) {
}
感谢您的帮助
克里斯
最佳答案
使用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 ms应该会导致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>