java 通过 HttpGet 对象检索数据时设置超时值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12270601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:16:24  来源:igfitidea点击:

Setting a timeout value when retrieving data via HttpGet object

javahttp

提问by acvcu

I have some Java code that I 'inherited' from a previous co-worker. Part of it connects to an outside URL using method GET and retrieves a small amount of XML for parsing. We've been having issues recently with this connection crashing our website due to the vendor website hanging and using up resources on our side. One issue is due to no timeouts being set when our code uses the HttpGet object. Is there a way to fine-tune timeouts using this object, or is there a better way to pull back this XML?

我有一些 Java 代码是我从以前的同事那里“继承”的。它的一部分使用方法 GET 连接到外部 URL 并检索少量 XML 进行解析。由于供应商网站挂起并耗尽了我们这边的资源,我们最近遇到了此连接使我们的网站崩溃的问题。一个问题是当我们的代码使用 HttpGet 对象时没有设置超时。有没有办法使用这个对象来微调超时,或者有没有更好的方法来拉回这个 XML?

Would I be better off using another API?

使用其他 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");

Thanks!

谢谢!

回答by MaVRoSCy

try this instead

试试这个

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

From Java HTTP Client Request with defined timeout

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