3

我有一些从以前的同事那里“继承”的 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");

谢谢!

4

1 回答 1

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");

来自具有定义超时的 Java HTTP 客户端请求

于 2012-09-04T20:22:40.117 回答