使用Apache HttpClient如何设置请求和响应的超时
我需要为我们对服务(而不是Web服务)发出的Http请求设置超时。我们正在使用Apache HTTP Client。我添加了这两行代码来设置请求超时和对服务的响应。
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
1)目前我已经将10秒设置为超时,因为我几乎立即看到来自服务的响应。我应该增加还是减少时间?
2)当响应超过10秒时会发生什么?它会引发异常吗?它会是什么异常?我还需要添加什么来在下面的代码中设置超时。
public HashMap<String, Object> getJSONData(String url) throw Exception{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
HttpHost proxy = new HttpHost(getProxy(), getProxyPort());
ConnRouteParams.setDefaultProxy(params, proxy);
URI uri;
InputStream data = null;
try {
uri = new URI(url);
HttpGet method = new HttpGet(uri);
HttpResponse response = httpClient.execute(method);
data = response.getEntity().getContent();
}
catch (Exception e) {
e.printStackTrace();
}
Reader r = new InputStreamReader(data);
HashMap<String, Object> jsonObj = (HashMap<String, Object>) GenericJSONUtil.fromJson(r);
return jsonObj;
}