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