用Apache发出http请求时,如何捕获InterruptedException? [英] How can I catch InterruptedException when making http request with Apache?

查看:246
本文介绍了用Apache发出http请求时,如何捕获InterruptedException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过Apache库发出http请求的Callable.但是,如果请求花费的时间太长,我想杀死该线程.为此,我可以中断Callable,但是我需要捕获InterruptedException才能停止自己.我该怎么办?

I have a Callable that makes a http request via Apache library. However, if the request takes too long, I would like to kill the thread. To do this, I can interrupt the Callable, but I need to catch the InterruptedException in order to stop myself. How can I do this?

private final class HelloWorker implements Callable<String> {
    private String url;

    public HelloWorker(String url) {
        this.url = url;
    }

    public CloseableHttpResponse call() throws Exception {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(getCustomSslConnectionSocketFactory())
                .build();

        return httpClient.execute(new HttpGet(url));
    }
}

private CloseableResponse getHttpResponse(String url) {
    ExecutorService executorService = Executors.newFixedThreadPool(threadPoolSize);
    Future<String> future = executorService.submit(new HelloWorker());

    try {  
        // try to get a response within 5 seconds
        return future.get(5, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        // kill the thread
        future.cancel(true);
    }
    return null;
}

注意future.cancel(true)不会杀死线程,因为它所做的只是中断线程,而且我的代码没有捕获InterruptedException.但是,由于httpClient.execute被阻止,我无法弄清楚该怎么做,也无法将工作划分为多个块.

Note future.cancel(true) doesn't kill the thread because all it does is interrupt the thread, and my code doesn't catch the InterruptedException. However, I cannot figure out how to do this since httpClient.execute is blocking, and I cannot divide the work into chunks.

在调用httpClient.execute()时仅捕获InterruptedException就足够了吗?

Would it be sufficient to just catch InterruptedException while calling httpClient.execute()?

    public CloseableHttpResponse call() throws Exception {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(getCustomSslConnectionSocketFactory())
                .build();
        try {
            return httpClient.execute(new HttpGet(url));
        } catch (InterruptedException) {
            return null;
        }
    }

推荐答案

为此,我可以中断Callable,但是我需要捕获InterruptedException才能停止自己.我该怎么办?

To do this, I can interrupt the Callable, but I need to catch the InterruptedException in order to stop myself. How can I do this?

不能. HttpClient的所有外部方法均不抛出InterruptedException.您无法捕获方法未引发的异常.中断线程只会导致 那些抛出InterruptedException的方法将其抛出.这包括Thread.sleep()Object.wait()等.其余方法必须测试Thread.currentThread().isInterrupted()才能看到中断标志.

You can't. None of the external methods of the HttpClient throw InterruptedException. You cannot catch an exception that is not thrown by the methods. Interrupting a thread causes only those methods that throw InterruptedException to throw it. This includes Thread.sleep(), Object.wait(), and others. The rest of the methods must test for Thread.currentThread().isInterrupted() to see the interrupt flag.

我建议设置用于设置套接字超时的http客户端参数.我不确定您正在使用哪个版本的Apache HttpClient,但是我们正在使用4.2.2并执行以下操作:

I recommend setting http client parameters that set the socket timeouts. I'm not sure which version of Apache HttpClient you are using but we are using 4.2.2 and do something like the following:

BasicHttpParams clientParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(clientParams, socketTimeoutMillis);
HttpConnectionParams.setSoTimeout(clientParams, socketTimeoutMillis);
HttpClient client = new DefaultHttpClient(clientParams);

这篇关于用Apache发出http请求时,如何捕获InterruptedException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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