我正在研究由我们公司开发的应用程序。它使用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.


    @ScadgeSince 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/

    10-10 13:09