如何正确关闭com.google.api.client.http.HttpResponse对象

时间:2017-12-12 20:27:37

标签: java httpresponse

我正在尝试关闭com.google.api.client.http.HttpResponse对象,但是我收到了Eclipse错误

  

未处理的异常类型IOException

response.disconnect();

以下是代码示例:

HttpRequest request = null;
HttpResponse response = null;

try {
    request = this.buildJsonApiRequest(apiUrl);
    response = this.execute(request);
    return response.parseAs(MyClass.class);
} catch (final IOException e) {
    throw new DaoException(e);
} finally {
    if (response != null) { 
        response.disconnect();
    }
}

代码在没有finally块的情况下工作,但是我担心许多响应对象被打开而没有关闭。这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

您需要将断开连接调用放在try-catch block内,因为根据Google API文档,该方法可能会抛出IOException:

public void disconnect() throws IOException

请点击此链接了解详情:

https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.20.0/com/google/api/client/http/HttpResponse#disconnect()

答案 1 :(得分:0)

这是对Eleazar Enrique的回答,即断开连接需要在try块内。这是一个如何更优雅地编写它并使其可重用的示例。

您可以创建一个实现autoCloseable的处理程序类,然后使用try-with-resource

public class HttpResponseHandler implements AutoCloseable {
    private HttpResponse response;
    public HttpResponseHandler(HttpResponse response) {
        this.response = response;
    }
}

public <T> T parseAs(Class<T> clazz) throws IOException {
    return response.parseAs(clazz);
}

@Override
public void close() {
    if (response != null) {
        try {
            response.disconnect();
        } catch (IOException ex) {}
    }
}

然后在你的代码中它将是这样的

HttpRequest request = this.buildJsonApiRequest(apiUrl);

try (HttpResponseHandler handler = new HttpResponseHandler(this.execute(request)) {
    return handler.parseAs(MyClass.class);
} catch (final IOException e) {
    throw new DaoException(e);
}

AutoCloseable将为您关闭连接,因此您不必在finally块中处理它。