java - Apache HttpClient API 中的 CloseableHttpClient 和 HttpClient 有什么区别?

标签 java apache http apache-httpclient-4.x

我正在研究我们公司开发的应用程序。它使用 Apache HttpClient 库。在源代码中,它使用 HttpClient 类来创建实例以连接到服务器。

我想了解 Apache HttpClient 并且我已经经历了 this set of examples .所有示例都使用 CloseableHttpClient 而不是 HttpClient。所以我认为CloseableHttpClientHttpClient 的扩展版本。如果是这种情况,我有两个问题:

  • 这两者有什么区别?
  • 建议在我的新开发中使用哪个类?

最佳答案

  • HttpClient API 的主要入口点是 HttpClient 接口(interface)。
  • HttpClient最基本的功能是执行HTTP方法。
  • HTTP 方法的执行涉及一个或多个 HTTP 请求/HTTP 响应交换,通常由 HttpClient 在内部处理。

  • CloseableHttpClient 是一个抽象类,它是 HttpClient 的基础实现,也实现了 java.io.Closeable。
  • 以下是最简单形式的请求执行过程示例:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost/");
    CloseableHttpResponse response = httpclient.execute(httpget);
    try {
        //do something
    } finally {
        response.close();
    }

  • HttpClient resource deallocation: When an instance CloseableHttpClient is no longer needed and is about to go out of scope the connection manager associated with it must be shut down by calling the CloseableHttpClient#close() method.

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        //do something
    } finally {
        httpclient.close();
    }

see the Reference to learn fundamentals.


@Scadge Since Java 7, Use of try-with-resources statement ensures that each resource is closed at the end of the statement. It can be used both for the client and for each response

try(CloseableHttpClient httpclient = HttpClients.createDefault()){

    // e.g. do this many times
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
    //do something
    }

    //do something else with httpclient here
}

关于java - Apache HttpClient API 中的 CloseableHttpClient 和 HttpClient 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21574478/

相关文章:

java - java中Add函数的问题

java - 如何移动 IntelliJ 文件选项卡?

php - CURL - 此请求需要 HTTP 身份验证

apache - 如何让 SPNEGO 与 mod_auth_kerb 一起工作?

java - 如何在 apache 中使用 HttpClient 从 Java Swing 登录页面调用 Servlet?

javascript - Node.JS HTTP 请求 - 分离回调函数

java - android.content.ActivityNotFoundException : No Activity found to handle Intent { act=login_filter (has extras) }

java - 无法通过 gmail smtp 发送消息

apache - 需要帮助将 Apache2 重写规则转换为 nginx

android - Cordova 错误 : Failed to fetch platform cordova-android//Error: cmd: Command failed with exit code ENOENT