我收到此错误:
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
如何解决?