Java 在使用Apache发出http请求时,如何捕获InterruptedException?

Java 在使用Apache发出http请求时,如何捕获InterruptedException?,java,multithreading,apache,threadpool,interrupt,Java,Multithreading,Apache,Threadpool,Interrupt,我有一个通过Apache库发出http请求的可调用函数。但是,如果请求花费的时间太长,我想终止线程。为此,我可以中断Callable,但我需要捕获InterruptedException以停止自己。我该怎么做 private final class HelloWorker implements Callable<String> { private String url; public HelloWorker(String url) { this.ur

我有一个通过Apache库发出http请求的可调用函数。但是,如果请求花费的时间太长,我想终止线程。为此,我可以中断Callable,但我需要捕获InterruptedException以停止自己。我该怎么做

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;
}
为此,我可以中断Callable,但我需要捕获InterruptedException以停止自己。我该怎么做

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;
}
你不能。
HttpClient
throw
InterruptedException
的任何外部方法。您无法捕获方法未引发的异常。中断线程只会导致那些抛出
InterruptedException
的方法抛出它。这包括
Thread.sleep()
Object.wait()
,以及其他。其余方法必须测试
Thread.currentThread().isInterrupted()
,以查看中断标志

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

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

一个
未来
会捕捉到你没有捕捉到的每一个
可丢弃的
.get()
将在您需要时提供给您。“但是,如果请求花费的时间太长,我希望终止线程”。不,你没有。您想设置超时。如果有帮助,请记住接受此消息。