我有一些我从以前的同事那里继承的Java代码。它的一部分使用方法GET连接到外部URL,并检索少量XML以进行解析。由于供应商网站挂起并耗尽了我们这方面的资源,我们最近因为此连接导致网站崩溃而遇到问题。一个问题是由于我们的代码使用HttpGet对象时没有设置超时。有没有办法使用这个对象微调超时,还是有更好的方法来撤回这个XML?
使用其他API会更好吗?
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1","foobar"));
URI uri = URIUtils.createURI("http", "myhost.com", -1, "mypath",
URLEncodedUtils.format(params, "UTF-8"), null);
// there is no timeout here??
HttpGet httpGet = new HttpGet(uri);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
String result = IOUtils.toString(httpResponse.getEntity()
.getContent(), "UTF-8");
谢谢!
答案 0 :(得分:7)
试试这个
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1","foobar"));
URI uri = URIUtils.createURI("http", "myhost.com", -1, "mypath",
URLEncodedUtils.format(params, "UTF-8"), null);
HttpGet httpGet = new HttpGet(uri);
HttpClient httpClient = new DefaultHttpClient();
// set the connection timeout value to 30 seconds (30000 milliseconds)
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
httpClient = new DefaultHttpClient(httpParams);
HttpResponse httpResponse = httpClient.execute(httpGet);
String result = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");