以下代码有一些问题。首先,它给了我一个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。
答案 0 :(得分:1)
我已经弄清楚问题是什么。我不得不通过代理连接(我们的浏览器会自动执行此操作并解释我在使用Web浏览器时获得响应的原因)。我只需要通过以下方式修改我的代码:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.url.com", 80));
URLConnection myURLConnection = myURL.openConnection(proxy);