通过HttpGet对象检索数据时设置超时值 [英] Setting a timeout value when retrieving data via HttpGet object

查看:158
本文介绍了通过HttpGet对象检索数据时设置超时值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

我会更好地使用其他API?

Would I be better off using another 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");

谢谢!

推荐答案

试试这个

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客户端请求

这篇关于通过HttpGet对象检索数据时设置超时值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆