关闭Apache CloseableHttpConnection并正确处理关闭异常

时间:2019-05-09 08:37:49

标签: java apache-httpclient-4.x

根据Apache documentation,每当您打开CloseableHttpClient时,也必须将其关闭。但是,CloseableHttpClientthrowsIOException的close方法。我在文档中找不到有关此异常的任何单词。连接即将失败的可能原因是什么?在这种情况下我该怎么办?

private void someMethod(){

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = createPostRequest(); //some custom build request.

    HttpResponse response;

    try{
        response = httpClient.execute(post);
    }catch(Exception e){
        handleException(e);
    }finally{
        try{
            httpClient.close()
        }catch(IOException e){
            //WHAT TO DO HERE ?!?!?
        }
    }
    doSomethingWith(response);
}

1 个答案:

答案 0 :(得分:0)

因为IOException永远不会发生,所以不需要处理IOException

TL; DR;
CloseableHttpClient是抽象类,它实现了接口Closeable。如您所见,Closeable::close方法声明了throws IOException,但是CloseableHttpClient使其成为了抽象方法。因此,CloseableHttpClient的子类应注意实现。

HttpClients::createDefault返回InternalHttpClient,它实现了Closeable::close方法,根本没有声明throws