Apache HttpClient API 中的 CloseableHttpClient 和 HttpClient 有什么区别? [英] What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

查看:49
本文介绍了Apache HttpClient API 中的 CloseableHttpClient 和 HttpClient 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm studying an application developed by our company. It uses the Apache HttpClient library. In the source code it uses the HttpClient class to create instances to connect to a server.

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

I want to learn about Apache HttpClient and I've gone trough this set of examples. All the examples use CloseableHttpClient instead of HttpClient. So I think CloseableHttpClient is an extended version of HttpClient. If this is the case I have two questions:

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

推荐答案

  • HttpClient API 的主要入口点是 HttpClient 接口.
  • HttpClient 最本质的功能是执行 HTTP 方法.
  • HTTP 方法的执行涉及一个或多个 HTTP 请求/HTTP 响应交换,通常由 HttpClient 内部处理.
    • CloseableHttpClient 是一个抽象类,它是 HttpClient 的基本实现,它也实现了 java.io.Closeable.
    • 以下是最简单形式的请求执行过程示例:

    • CloseableHttpClient is an abstract class which is the base implementation of HttpClient that also implements java.io.Closeable.
    • Here is an example of request execution process in its simplest form:

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

    • HttpClient 资源释放: 当不再需要 CloseableHttpClient 实例并且即将超出范围时,必须通过调用 CloseableHttpClient#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.

    @Scudge从 Java 7 开始,使用 try-with-resources 语句确保每个资源在语句结束时关闭.它可以用于客户端和每个响应

    @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
    }
    

    这篇关于Apache HttpClient API 中的 CloseableHttpClient 和 HttpClient 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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