下面的代码有一些问题。首先,它给了我一个 SocketTimeoutException。几天前这工作得很好,但现在它抛出了这个错误。我不确定如何将问题追溯到源头。我尝试增加超时(我真的不认为最终会起作用),但它总是在 18 秒后超时。更奇怪的是,当我尝试从其他东西(例如http://mysafeinfo.com/api/data?list=englishmonarchs&format=json)获取 JSON 文件时,该 URL 有效。我已经等了大约一天,问题仍然存在。我能做些什么来解决这个问题吗?
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class SocketTimeoutError {
public static void main(String args[]) {
URL myURL;
TimerTask task = null;
try {
myURL = new URL(
"https://maps.googleapis.com/maps/api/geocode/json?address=Chicago+Illinois");
URLConnection conn = myURL.openConnection();
conn.connect();
conn.setConnectTimeout(4 * 600000);
conn.setReadTimeout(4 * 600000);
//
Timer timer = new Timer();
task = new TimerTask() {
int time = 0;
public void run() {
System.out.println(time++);
}
};
//
System.out.println("Connecting..." + "Timeout="
+ conn.getConnectTimeout());
timer.scheduleAtFixedRate(task, 0, 1000);
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
task.cancel();
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(in);
String status = (String) jsonObject.get("status");
System.out.println(status);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
这是我的控制台输出:
Connecting...Timeout=2400000
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.security.ssl.InputRecord.readFully(Unknown Source)
at sun.security.ssl.InputRecord.read(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
at sun.security.ssl.AppInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read1(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at SocketTimeoutError.main(SocketTimeoutError.java:38)
---编辑---
我一直在我的工作机器上这样做。我刚刚在我的家用电脑上尝试了这段代码,它工作得很好。此外,我工作的公司拥有 Google for Work 许可证。不过,我不明白这可能是公司和谷歌服务器之间的网络问题,因为我能够在我的 Chrome 浏览器中查看 json。