使用Apache HttpClient如何在请求和响应上设置TIMEOUT [英] Using Apache HttpClient how to set the TIMEOUT on a request and response

查看:586
本文介绍了使用Apache HttpClient如何在请求和响应上设置TIMEOUT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为我们对服务(不是Web服务)发出的Http请求设置时间。我们正在使用Apache HTTP Client。我添加了这两行代码来设置请​​求和响应服务的超时时间。

I need to set time out for the Http Request we make to a service (not a web service). We are using Apache HTTP Client. I have added these 2 lines of code to set the time out on request and response to the service.

HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);

1)目前我已设置10秒作为超时,因为我看到来自服务的响应差不多瞬间。我应该增加还是减少时间?

1) Currently I have set 10 seconds as the timeout since I see the response coming from the service almost instantaneously. Should I increase or decrease the timing?

2)当响应时间超过10秒时会发生什么?它会抛出异常,会有什么异常吗?在下面的代码中是否需要添加任何其他内容来设置超时。

2) What will happen when response is takes more than 10 seconds? Will it throw exception and what exception will it be? Is there any thing else I need to add to set the time out in the below code.

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;
}


推荐答案

你会看到例外情况将是 ConnectTimeoutException SocketTimeoutException 。您使用的实际超时值应该是您的应用程序愿意等待的最长时间。关于读取超时的一个重要注意事项是它对应于套接字读取的超时。因此,不是完整响应到达的时间,而是单个套接字读取的时间。因此,如果有4个套接字读取,每个读取9秒,则总读取时间为9 * 4 = 36秒。

The exceptions you'll see will be ConnectTimeoutException and SocketTimeoutException. The actual timeout values you use should be the maximum time your application is willing to wait. One important note about the read timeout is that it corresponds to the timeout on a socket read. So it's not the time allowed for the full response to arrive, but rather the time given to a single socket read. So if there are 4 socket reads, each taking 9 seconds, your total read time is 9 * 4 = 36 seconds.

如果要指定总时间响应到达(包括连接和总读取时间),您可以将调用包装在一个线程中并使用线程超时。例如,我通常做这样的事情:

If you want to specify a total time for the response to arrive (including connect and total read time), you can wrap the call in a thread and use a thread timeout for that. For example, I usually do something like this:

Future<T> future = null;
future = pool.submit(new Callable<T>() {
    public T call() {
        return executeImpl(url);
    }   
}); 

try {
    return future.get(10, TimeUnit.SECONDS);
}   
catch (InterruptedException e) {
    log.warn("task interrupted", name);
}   
catch (ExecutionException e) {
    log.error(name + " execution exception", e); 
}   
catch (TimeoutException e) {
    log.debug("future timed out", name);
}

上面代码中的一些假设是:1)这是一个函数使用url参数,2)它在具有名称变量的类中,3)log是log4j实例,4)pool是一个线程池执行器。请注意,即使您使用线程超时,您还应该在HttpClient上指定连接和套接字超时,以便慢速请求不会占用线程池中的资源。另请注意,我使用线程池,因为通常我在Web服务中使用它,因此线程池在一堆tomcat线程中共享。你的环境可能不同,你可能更愿意为每次调用简单地生成一个新线程。

Some assumptions made in the code above are: 1) this is in a function with a url parameter, 2) it's in a class with a name variable, 3) log is a log4j instance, and 4) pool is a some thread pool executor. Note that even if you use a thread timeout, you should also specify a connect and socket timeout on the HttpClient, so that slow requests don't eat up the resources in the thread pool. Also note that I use a thread pool because typically I use this in a web service so the thread pool is shared across a bunch of tomcat threads. You're environment may be different, and you may prefer to simply spawn a new thread for each call.

另外,我通常会看到通过成员函数设置的超时时间params,如下所示:

Also, I've usually see the timeouts set via member functions of the params, like this:

params.setConnectionTimeout(10000);
params.setSoTimeout(10000);

但也许你的语法也可以(不确定)。

But perhaps your syntax works as well (not sure).

这篇关于使用Apache HttpClient如何在请求和响应上设置TIMEOUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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