我收到此错误:
java.net.SocketTimeoutException: Read timed out
http://api.trove.nla.gov.au/result?key=<KEY HERE>&zone=all&reclevel=brief&q=%20am%20only%20yours%20fear&encoding=json
Exception in thread "main" java.lang.NullPointerException at
trove.connect.TroveService.QueryTrove(TroveService.java:134) at
datasetconverter.CsvReader2.main(CsvReader2.java:64) Java Result: 1
BUILD SUCCESSFUL (total time: 1 minute 41 seconds)
当我执行我的代码时:
public String getJSON(String url, int timeout) throws IOException, Exception {
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 504:
case 503:
Thread.sleep(10000);
this.QueryTrove(url);
break;
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
System.out.println(ex);
System.out.println(url);
} catch (IOException ex) {
System.out.println(ex);
System.out.println(url);
}
return null;
}
public int QueryTrove(String query) throws Exception{
int sum =0;
String json = getJSON("http://api.trove.nla.gov.au/result?key=<KEY HERE>&zone=all&reclevel=brief&q="+query+"&encoding=json",10000);
Gson gson = new Gson();
JsonResponse r = gson.fromJson(json, JsonResponse.class);
for (Zone zone : r.getResponse().getZones()) {
sum = sum + Integer.parseInt(zone.records.getTotal());
}
return sum;
}
这是因为setConnectionTimeout
又如何解决?
答案 0 :(得分:5)
发生读取超时是因为服务器花费的时间比“read-timeout”参数要长。 但假设您有一个合理的读取超时值(假设30秒),它并不一定意味着问题是您的读取超时太短,可能是服务器卡住而且永远不会返回答案。
要诊断,您可以执行以下操作:
如果服务器回答您的浏览器而不是您的Java应用程序,那么首先要确保您正在调用完全相同的URL。除此之外,由于您的USER-AGENT,服务器可能会忽略您,请尝试模拟真实的浏览器。
另外只是一个友好的建议,我会将超时作为参数传递,只需定义一个合理的超时并直接使用它,除非它是一个非常不寻常的用例,没有机构想要在使用这种抽象时传递超时