Apache HttpClient - 快速指南


Apache HttpClient - 概述

超文本传输​​协议 (HTTP) 是分布式协作超媒体信息系统的应用程序级协议。这是自 1990 年以来万维网(即 Internet)数据通信的基础。HTTP 是一种通用且无状态的协议,可以用于其他目的,也可以使用其请求方法、错误代码和标头的扩展。

基本上,HTTP 是基于 TCP/IP 的通信协议,用于在万维网上传递数据(HTML 文件、图像文件、查询结果等)。默认端口是 TCP 80,但也可以使用其他端口。它为计算机之间的通信提供了一种标准化的方式。HTTP 规范定义了客户端的请求数据如何构造并发送到服务器,以及服务器如何响应这些请求。

什么是Http客户端

Http client是一个传输库,它驻留在客户端,发送和接收HTTP消息。它提供了最新的、功能丰富且高效的实现,符合最新的 HTTP 标准。

除了使用客户端库之外,还可以构建基于 HTTP 的应用程序,例如 Web 浏览器、Web 服务客户端等。

Http客户端的特点

以下是 Http 客户端的突出特点 -

  • HttpClient 库实现了所有可用的 HTTP 方法。

  • HttpClient 库提供 API 来使用安全套接字层协议来保护请求。

  • 使用 HttpClient,您可以使用代理建立连接。

  • 您可以使用基本、摘要、NTLMv1、NTLMv2、NTLM2 会话等身份验证方案对连接进行身份验证。

  • HttpClient 库支持通过多线程发送请求。它使用ClientConnectionPoolManager管理从各个线程建立的多个连接。

  • 使用 Apache HttpClient 库,您可以设置连接超时。

Apache HttpClient - 环境设置

在本章中,我们将介绍如何在 Eclipse IDE 中为 HttpClient 设置环境。在继续安装之前,请确保您的系统中已安装 Eclipse。如果没有,请下载并安装 Eclipse。

有关 Eclipse 的更多信息,请参阅我们的Eclipse 教程

第 1 步 - 下载依赖 JAR 文件

打开HttpClient(组件)网站官方主页,进入下载页面

HttpComponents 下载

然后,下载最新稳定版本的HttpClient。在整个教程中,我们使用版本 4.5.6,因此下载文件4.5.6.zip

在下载的文件夹中,您将找到一个名为lib的文件夹,其中包含要添加到项目的类路径中以使用 HttpClient 所需的 Jar 文件。

第 2 步 - 创建项目并设置构建路径

打开 eclipse 并创建一个示例项目。右键单击项目,选择选项“构建路径”→“配置构建路径”,如下所示。

构建路径

“库”选项卡的“Java 构建路径”框架中,单击“添加外部 JAR”

添加外部罐子

然后选择 lib 文件夹中的所有 jar 文件,然后单击“应用并关闭”

Jar 文件

您已准备好在 eclipse 中使用 HttpClient 库。

Apache HttpClient - Http 获取请求

GET 方法用于使用给定 URI 从给定服务器检索信息。使用 GET 的请求应该只检索数据,而不应该对数据产生其他影响。

HttpClient API 提供了一个名为HttpGet的类,它表示 get 请求方法。

按照下面给出的步骤使用 HttpClient 库发送 get 请求

第 1 步 - 创建 HttpClient 对象

HttpClients类的createDefault ()方法返回一个CloseableHttpClient对象,它是HttpClient接口的基本实现。

使用此方法,创建一个 HttpClient 对象,如下所示 -

CloseableHttpClient httpclient = HttpClients.createDefault();

第 2 步 - 创建 HttpGet 对象

HttpGet类表示 HTTPGET 请求,该请求使用 URI 检索给定服务器的信息

通过实例化此类来创建 HTTP GET 请求。此类的构造函数接受表示 URI 的字符串值。

HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/");

第 3 步 - 执行获取请求

CloseableHttpClient类的execute ()方法接受HttpUriRequest(接口)对象(即HttpGet、HttpPost、HttpPut、HttpHead 等)并返回响应对象。

使用此方法执行请求,如下所示 -

HttpResponse httpresponse = httpclient.execute(httpget);

例子

以下示例演示了使用 HttpClient 库执行 HTTP GET 请求。

import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpGetExample {
 
   public static void main(String args[]) throws Exception{
 
      //Creating a HttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

      //Creating a HttpGet object
      HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/ ");

      //Printing the method used
      System.out.println("Request Type: "+httpget.getMethod());

      //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(httpget);

      Scanner sc = new Scanner(httpresponse.getEntity().getContent());

      //Printing the status line
      System.out.println(httpresponse.getStatusLine());
      while(sc.hasNext()) {
         System.out.println(sc.nextLine());
      }
   }
} 

输出

上述程序生成以下输出 -

Request Type: GET
<!DOCTYPE html>
<!--[if IE 8]><html class = "ie ie8"> <![endif]-->
<!--[if IE 9]><html class = "ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html lang = "en-US"> <!--<![endif]-->
<head>
<!-- Basic -->
<meta charset = "utf-8">
<title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java
i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible,
LOLCODE, Current Affairs 2018, Apache Commons Collections</title>
<meta name = "Description" content = "Parallax Scrolling, Java Cryptography, YAML,
Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common
CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache
Commons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC),
Logo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow"/>
<meta name = "Keywords" content = "Python Data Science, Java i18n, GitLab,
TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson,
TestLink, Inter Process Communication (IPC), Logo"/>
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device-width,initial-scale = 1.0,userscalable = yes">
<link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css"
rel = "stylesheet" type = "text/css" />
<link rel = "stylesheet" href="/questions/css/home.css?v = 3" />
<script src = "/questions/js/jquery.min.js"></script>
<script src = "/questions/js/fontawesome.js"></script>
<script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script>
</head>
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
</script>
</body>
</html>

Apache HttpClient - Http Post 请求

POST请求用于向服务器发送数据;例如客户信息、文件上传等,使用HTML表单。

HttpClient API 提供了一个名为HttpPost的类,它表示 POST 请求。

按照下面给出的步骤使用 HttpClient 库发送 HTTP POST 请求。

第 1 步 - 创建 HttpClient 对象

HttpClients类的createDefault ()方法返回CloseableHttpClient类的对象,该类是HttpClient接口的基本实现。

使用此方法创建一个 HttpClient 对象。

CloseableHttpClient httpClient = HttpClients.createDefault();

第 2 步 - 创建 HttpPost 对象

HttpPost类表示HTTP POST请求。这会发送所需的数据并使用 URI 检索给定服务器的信息。

通过实例化HttpPost类来创建此请求,并将表示 URI 的字符串值作为参数传递给其构造函数。

HttpGet httpGet = new HttpGet("https://www.tutorialspoint.com/");

第 3 步 - 执行获取请求

CloseableHttpClient 对象的execute ()方法接受HttpUriRequest(接口)对象(即HttpGet、HttpPost、HttpPut、HttpHead 等)并返回响应对象。

HttpResponse httpResponse = httpclient.execute(httpget);

例子

以下示例演示了使用 HttpClient 库执行 HTTP POST 请求。

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpPostExample {
 
   public static void main(String args[]) throws Exception{
 
      //Creating a HttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

      //Creating a HttpGet object
      HttpPost httppost = new HttpPost("https://www.tutorialspoint.com/");

      //Printing the method used
      System.out.println("Request Type: "+httppost.getMethod());

      //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(httppost);

      Scanner sc = new Scanner(httpresponse.getEntity().getContent());

      //Printing the status line
      System.out.println(httpresponse.getStatusLine());
      while(sc.hasNext()) {
         System.out.println(sc.nextLine());
      }
   }
}

输出

上述程序生成以下输出。

Request Type: POST
<!DOCTYPE html>
<!--[if IE 8]><html class = "ie ie8"> <![endif]-->
<!--[if IE 9]><html class = "ie ie9"> <![endif]-->
<!--[if gt IE 9]><!--> 
<html lang = "en-US"> <!--<![endif]-->
<head>
<!-- Basic -->
<meta charset = "utf-8">
<title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java
i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible,
LOLCODE, Current Affairs 2018, Apache Commons Collections</title>
<meta name = "Description" content = "Parallax Scrolling, Java Cryptography, YAML,
Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common
CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache
Commons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC),
Logo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow"/>
<meta name = "Keywords" content="Python Data Science, Java i18n, GitLab,
TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson,
TestLink, Inter Process Communication (IPC), Logo"/>
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" conten t= "width = device-width,initial-scale = 1.0,userscalable = yes">
<link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css"
rel = "stylesheet" type = "text/css" />
<link rel = "stylesheet" href = "/questions/css/home.css?v = 3" />
<script src = "/questions/js/jquery.min.js"></script>
<script src = "/questions/js/fontawesome.js"></script>
<script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script>
</head>
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
</script>
</body>
</html>

Apache HttpClient - 响应处理程序

建议使用响应处理程序处理 HTTP 响应。在本章中,我们将讨论如何创建响应处理程序以及如何使用它们来处理响应。

如果您使用响应处理程序,所有 HTTP 连接将自动释放。

创建响应处理程序

HttpClient API在 org.apache.http.client 包中提供了一个称为ResponseHandler 的接口为了创建响应处理程序,请实现此接口并重写其handleResponse()方法。

每个响应都有一个状态代码,如果状态代码在 200 到 300 之间,则表示该操作已成功接收、理解和接受。因此,在我们的示例中,我们将处理具有此类状态代码的响应实体。

使用响应处理程序执行请求

按照下面给出的步骤使用响应处理程序执行请求。

第 1 步 - 创建 HttpClient 对象

HttpClients类的createDefault ()方法返回CloseableHttpClient类的对象,该类是HttpClient接口的基本实现。使用此方法创建一个 HttpClient 对象

CloseableHttpClient httpclient = HttpClients.createDefault();

第 2 步 - 实例化响应处理程序

使用以下代码行实例化上面创建的响应处理程序对象 -

ResponseHandler<String> responseHandler = new MyResponseHandler(); 

第 3 步 - 创建 HttpGet 对象

HttpGet类表示 HTTP GET 请求,该请求使用 URI 检索给定服务器的信息

通过实例化 HttpGet 类并将表示 URI 的字符串作为参数传递给其构造函数来创建 HttpGet 请求。

ResponseHandler<String> responseHandler = new MyResponseHandler(); 

第 4 步 - 使用响应处理程序执行 Get 请求

CloseableHttpClient类有一个execute()方法的变体它接受两个对象ResponseHandler和HttpUriRequest,并返回一个响应对象。

String httpResponse = httpclient.execute(httpget, responseHandler);

例子

以下示例演示了响应处理程序的用法。

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

class MyResponseHandler implements ResponseHandler<String>{
 
   public String handleResponse(final HttpResponse response) throws IOException{

      //Get the status of the response
      int status = response.getStatusLine().getStatusCode();
      if (status >= 200 && status < 300) {
         HttpEntity entity = response.getEntity();
         if(entity == null) {
            return "";
         } else {
            return EntityUtils.toString(entity);
         }

      } else {
         return ""+status;
      }
   }
}

public class ResponseHandlerExample {
   
   public static void main(String args[]) throws Exception{
 
      //Create an HttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

      //instantiate the response handler
      ResponseHandler<String> responseHandler = new MyResponseHandler();

      //Create an HttpGet object
      HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/");

      //Execute the Get request by passing the response handler object and HttpGet object
      String httpresponse = httpclient.execute(httpget, responseHandler);

      System.out.println(httpresponse);
   }
}

输出

上述程序生成以下输出 -

<!DOCTYPE html>
<!--[if IE 8]><html class = "ie ie8"> <![endif]-->
<!--[if IE 9]><html class = "ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html lang = "en-US"> <!--<![endif]-->
<head>
<!-- Basic -->
<meta charset = "utf-8">
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device-width,initial-scale = 1.0,userscalable = yes">
<link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css"
rel = "stylesheet" type = "text/css" />
<link rel = "stylesheet" href = "/questions/css/home.css?v = 3" />
<script src = "/questions/js/jquery.min.js"></script>
<script src = "/questions/js/fontawesome.js"></script>
<script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script>
</head>
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-232293-17');
</script>
</body>

Apache HttpClient - 关闭连接

如果您手动处理 HTTP 响应而不是使用响应处理程序,则需要自行关闭所有 http 连接。本章介绍如何手动关闭连接。

手动关闭 HTTP 连接时,请按照以下步骤操作:

第 1 步 - 创建 HttpClient 对象

HttpClients类的createDefault ()方法返回CloseableHttpClient类的对象,该类是 HttpClient 接口的基本实现。

使用此方法,创建一个HttpClient对象,如下所示 -

CloseableHttpClient httpClient = HttpClients.createDefault();

第 2 步 - 启动 try-finally 块

启动一个try-finally块,将剩余的代码写入try块中的程序中,并在finally块中关闭CloseableHttpClient对象。

CloseableHttpClient httpClient = HttpClients.createDefault();
try{
   //Remaining code . . . . . . . . . . . . . . .
}finally{
   httpClient.close();
}

第 3 步 - 创建 HttpGet 对象

HttpGet类表示 HTTP GET 请求,该请求使用 URI 检索给定服务器的信息

通过传递表示 URI 的字符串来实例化 HttpGet 类,从而创建 HTTP GET 请求。

HttpGet httpGet = new HttpGet("https://www.tutorialspoint.com/");

第 4 步 - 执行 Get 请求

CloseableHttpClient对象的execute ()方法接受HttpUriRequest(接口)对象(即HttpGet、HttpPost、HttpPut、HttpHead 等)并返回响应对象。

使用给定方法执行请求 -

HttpResponse httpResponse = httpclient.execute(httpGet);

第 5 步 - 开始另一个(嵌套的)try-finally

启动另一个 try-finally 块(嵌套在前面的 try-finally 中),将剩余的代码写入此 try 块中的程序中,并在 finally 块中关闭 HttpResponse 对象。

CloseableHttpClient httpclient = HttpClients.createDefault();
try{
   . . . . . . .
   . . . . . . .
   CloseableHttpResponse httpresponse = httpclient.execute(httpget);
   try{
      . . . . . . .
      . . . . . . .
   }finally{
      httpresponse.close();
   }
}finally{
   httpclient.close();
}

例子

每当您创建/获取请求、响应流等对象时,请在下一行中启动一个 try finally 块,在 try 中编写剩余的代码,并在 finally 块中关闭相应的对象,如以下程序所示 -

import java.util.Scanner;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class CloseConnectionExample {
   
   public static void main(String args[])throws Exception{
 
      //Create an HttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

      try{
         //Create an HttpGet object
         HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/");

         //Execute the Get request
         CloseableHttpResponse httpresponse = httpclient.execute(httpget);

         try{
            Scanner sc = new Scanner(httpresponse.getEntity().getContent());
            while(sc.hasNext()) {
               System.out.println(sc.nextLine());
            }
         }finally{
            httpresponse.close();
         }
      }finally{
         httpclient.close();
      }
   }
}

输出

执行上述程序时,会生成以下输出 -

<!DOCTYPE html>
<!--[if IE 8]><html class = "ie ie8"> <![endif]-->
<!--[if IE 9]><html class = "ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html lang = "en-US"> <!--<![endif]-->
<head>
<!-- Basic -->
<meta charset = "utf-8">
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device-width,initial-scale = 1.0,userscalable = yes">
<link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css"
rel = "stylesheet" type = "text/css" />
<link rel = "stylesheet" href = "/questions/css/home.css?v = 3" />
<script src = "/questions/js/jquery.min.js"></script>
<script src = "/questions/js/fontawesome.js"></script>
<script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script>
</head>
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . 
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-232293-17');
</script>
</body>
</html>

Apache HttpClient - 中止请求

您可以使用abort()方法中止当前的 HTTP 请求,即调用该方法后,对于特定请求,将中止该请求的执行。

如果在一次执行后调用该方法,则不会影响该次执行的响应,并且会中止后续执行。

例子

如果您观察以下示例,我们已经创建了一个 HttpGet 请求,并使用getMethod()打印了使用的请求格式。

然后,我们使用相同的请求执行了另一次执行。再次使用第一次执行打印状态行。最后打印第二次执行的状态行。

如前所述,打印第一次执行(在 abort 方法之前执行)的响应(包括在 abort 方法之后写入的第二个状态行),并且在 abort 方法之后当前请求的所有后续执行都会失败,调用例外。

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpGetExample {
   public static void main(String args[]) throws Exception{
   
      //Creating an HttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

      //Creating an HttpGet object
      HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/");

      //Printing the method used
      System.out.println(httpget.getMethod());
 
      //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(httpget);

      //Printing the status line
      System.out.println(httpresponse.getStatusLine());

      httpget.abort();
      System.out.println(httpresponse.getEntity().getContentLength());
 
      //Executing the Get request
      HttpResponse httpresponse2 = httpclient.execute(httpget);
      System.out.println(httpresponse2.getStatusLine());
   }
}

输出

执行时,上述程序生成以下输出 -

On executing, the above program generates the following output.
GET
HTTP/1.1 200 OK
-1
Exception in thread "main" org.apache.http.impl.execchain.RequestAbortedException:
Request aborted
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:180)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
at HttpGetExample.main(HttpGetExample.java:32)

Apache HttpClient - 拦截器

拦截器是那些有助于阻止或改变请求或响应的拦截器。协议拦截器通常作用于特定标头或一组相关标头。HttpClient 库提供对拦截器的支持。

请求拦截器

HttpRequestInterceptor接口代表请求拦截器。该接口包含一个称为进程的方法,您需要在其中编写代码块来拦截请求。

在客户端,此方法在将请求发送到服务器之前验证/处理请求,而在服务器端,此方法在评估请求正文之前执行。

创建请求拦截器

您可以按照下面给出的步骤创建请求拦截器。

第 1 步 - 创建 HttpRequestInterceptor 对象

通过实现其抽象方法process来创建HttpRequestInterceptor接口的对象。

HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {

@Override
 public void process(HttpRequest request, HttpContext context) throws
HttpException, IOException {
   //Method implementation . . . . .
};

第 2 步 - 实例化 CloseableHttpClient 对象

通过添加上面创建的拦截器来构建自定义CloseableHttpClient对象,如下所示 -

//Creating a CloseableHttpClient object
CloseableHttpClient httpclient =
HttpClients.custom().addInterceptorFirst(requestInterceptor).build();

使用此对象,您可以照常执行请求。

例子

以下示例演示了请求拦截器的用法。在此示例中,我们创建了一个 HTTP GET 请求对象并向其添加了三个标头:sample-header、demoheader 和 test-header。

在拦截器的processor()方法中,我们正在验证发送的请求的标头;如果这些标头中的任何一个是example-header,我们将尝试删除它并显示该特定请求的标头列表。

import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HttpContext;

public class InterceptorsExample {
 
   public static void main(String args[]) throws Exception{
      
      //Creating an HttpRequestInterceptor
      HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {
         @Override
         public void process(HttpRequest request, HttpContext context) throws
         HttpException, IOException {
            if(request.containsHeader("sample-header")) {
               System.out.println("Contains header sample-header, removing it..");
               request.removeHeaders("sample-header"); 
            }
            //Printing remaining list of headers
            Header[] headers= request.getAllHeaders();
            for (int i = 0; i<headers.length;i++) {
               System.out.println(headers[i].getName());
            }
         }
      };

      //Creating a CloseableHttpClient object
      CloseableHttpClient httpclient =
      HttpClients.custom().addInterceptorFirst(requestInterceptor).build();

      //Creating a request object
      HttpGet httpget1 = new HttpGet("https://www.tutorialspoint.com/");

      //Setting the header to it
      httpget1.setHeader(new BasicHeader("sample-header","My first header"));
      httpget1.setHeader(new BasicHeader("demo-header","My second header"));
      httpget1.setHeader(new BasicHeader("test-header","My third header"));

      //Executing the request
      HttpResponse httpresponse = httpclient.execute(httpget1);

      //Printing the status line
      System.out.println(httpresponse.getStatusLine());
   }
}

输出

执行上述程序时,会生成以下输出 -

Contains header sample-header, removing it..
demo-header
test-header
HTTP/1.1 200 OK

响应拦截器

HttpResponseInterceptor接口代表响应拦截器。该接口包含一个称为process()的方法。在此方法中,您需要编写代码块来拦截响应。

在服务器端,此方法在将响应发送到客户端之前验证/处理响应,而在客户端,此方法在评估响应正文之前执行。

创建响应拦截器

您可以按照下面给出的步骤创建响应拦截器 -

第 1 步 - 创建 HttpResponseInterceptor 对象

通过实现HttpResponseInterceptor接口的抽象方法process创建一个对象。

HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
   @Override
   public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
      //Method implementation . . . . . . . .
   }
};

第2步:实例化CloseableHttpClient对象

通过添加上面创建的拦截器来构建自定义CloseableHttpClient对象,如下所示 -

//Creating a CloseableHttpClient object
CloseableHttpClient httpclient =
HttpClients.custom().addInterceptorFirst(responseInterceptor).build();

使用此对象,您可以照常执行请求。

例子

以下示例演示了响应拦截器的用法。在此示例中,我们向处理器中的响应添加了三个标头:sample-header、demo-header 和 test-header。

执行请求并获取响应后,我们使用getAllHeaders()方法打印响应的所有标头的名称。

在输出中,您可以观察列表中三个标头的名称。

import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;

public class ResponseInterceptorsExample {

   public static void main(String args[]) throws Exception{
      
      //Creating an HttpRequestInterceptor
      HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
         @Override
         public void process(HttpResponse response, HttpContext context) throws
         HttpException, IOException {
            System.out.println("Adding header sample_header, demo-header, test_header to the response");
            response.setHeader("sample-header", "My first header");
            response.setHeader("demo-header", "My second header");
            response.setHeader("test-header", "My third header"); 
         }
      };

      //Creating a CloseableHttpClient object
      CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(responseInterceptor).build();

      //Creating a request object
      HttpGet httpget1 = new HttpGet("https://www.tutorialspoint.com/");

      //Executing the request
      HttpResponse httpresponse = httpclient.execute(httpget1); 

      //Printing remaining list of headers
      Header[] headers = httpresponse.getAllHeaders();
 
      for (int i = 0; i<headers.length;i++) {
         System.out.println(headers[i].getName());
      }
   }
}

输出

执行时,上述程序生成以下结果 -

On executing the above program generates the following output.
Adding header sample_header, demo-header, test_header to the response
Accept-Ranges
Access-Control-Allow-Headers
Access-Control-Allow-Origin
Cache-Control
Content-Type
Date
Expires
Last-Modified
Server
Vary
X-Cache
sample-header
demo-header
test-header

Apache HttpClient - 用户身份验证

使用HttpClient,您可以连接到需要用户名和密码的网站。本章说明如何对要求用户名和密码的站点执行客户端请求。

第 1 步 - 创建 CredentialsProvider 对象

CredentialsProvider接口维护一个集合保存用户登录凭据。您可以通过实例化BasicCredentialsProvider类(该接口的默认实现)来创建其对象。

CredentialsProvider credentialsPovider = new BasicCredentialsProvider();

第 2 步 - 设置凭据

您可以使用setCredentials()方法将所需的凭据设置到 CredentialsProvider 对象。

该方法接受两个对象,如下所示 -

  • AuthScope 对象- 指定详细信息(如主机名、端口号和身份验证方案名称)的身份验证范围。

  • 凭据对象- 指定凭据(用户名、密码)。

使用主机和代理的setCredentials()方法设置凭据,如下所示 -

credsProvider.setCredentials(new AuthScope("example.com", 80), 
   new UsernamePasswordCredentials("user", "mypass"));
credsProvider.setCredentials(new AuthScope("localhost", 8000), 
   new UsernamePasswordCredentials("abc", "passwd"));

第 3 步 - 创建 HttpClientBuilder 对象

使用HttpClients类的custom()方法创建HttpClientBuilder

//Creating the HttpClientBuilder
HttpClientBuilder clientbuilder = HttpClients.custom();

第 4 步 - 设置凭证Povider

您可以使用setDefaultCredentialsProvider()方法将上面创建的凭据Povider 对象设置为 HttpClientBuilder 。

通过将上一步中创建的 CredentialProvider 对象传递给CredentialsProvider object()方法,将其设置为客户端构建器,如下所示。

clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);

第 5 步 - 构建 CloseableHttpClient

使用HttpClientBuilder类的build()方法构建CloseableHttpClient对象。

CloseableHttpClient httpclient = clientbuilder.build()

第 6 步 - 创建 HttpGet 对象并执行它

通过实例化 HttpGet 类来创建 HttpRequest 对象。使用execute()方法执行此请求。

//Creating a HttpGet object
HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/ ");

//Executing the Get request
HttpResponse httpresponse = httpclient.execute(httpget);

例子

以下是一个示例程序,演示了如何对需要用户身份验证的目标站点执行 HTTP 请求。

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;

public class UserAuthenticationExample {
   
   public static void main(String args[]) throws Exception{
      
      //Create an object of credentialsProvider
      CredentialsProvider credentialsPovider = new BasicCredentialsProvider();

      //Set the credentials
      AuthScope scope = new AuthScope("https://www.tutorialspoint.com/questions/", 80);
      
      Credentials credentials = new UsernamePasswordCredentials("USERNAME", "PASSWORD");
      credentialsPovider.setCredentials(scope,credentials);

      //Creating the HttpClientBuilder
      HttpClientBuilder clientbuilder = HttpClients.custom();

      //Setting the credentials
      clientbuilder = clientbuilder.setDefaultCredentialsProvider(credentialsPovider);

      //Building the CloseableHttpClient object
      CloseableHttpClient httpclient = clientbuilder.build();

      //Creating a HttpGet object
      HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/questions/index.php");

      //Printing the method used
      System.out.println(httpget.getMethod()); 

      //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(httpget);

      //Printing the status line
      System.out.println(httpresponse.getStatusLine());
      int statusCode = httpresponse.getStatusLine().getStatusCode();
      System.out.println(statusCode);

      Header[] headers= httpresponse.getAllHeaders();
      for (int i = 0; i<headers.length;i++) {
         System.out.println(headers[i].getName());
      }
   }
}

输出

执行时,上述程序会生成以下输出。

GET
HTTP/1.1 200 OK
200

Apache HttpClient - 使用代理

代理服务器是客户端和互联网之间的中间服务器。代理服务器提供以下基本功能 -

  • 防火墙和网络数据过滤

  • 网络连接共享

  • 数据缓存

使用 HttpClient 库,您可以使用代理发送 HTTP 请求。请按照以下步骤操作 -

第 1 步 - 创建 HttpHost 对象

通过将表示代理主机名称(您需要从中发送请求)的字符串参数传递给其构造函数,实例化org.apache.httpHttpHost类。

//Creating an HttpHost object for proxy
HttpHost proxyHost = new HttpHost("localhost"); 

同样的方式,创建另一个HttpHost对象来表示需要发送请求的目标主机。

//Creating an HttpHost object for target
HttpHost targetHost = new HttpHost("google.com");

第 2 步 - 创建 HttpRoutePlanner 对象

HttpRoutePlanner接口计算到指定主机路由。通过实例化DefaultProxyRoutePlanner类(该接口的实现)来创建该接口的对象。作为其构造函数的参数,传递上面创建的代理主机 -

//creating a RoutePlanner object
HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyhost);

第 3 步 - 将路线规划器设置为客户端构建器

使用HttpClients类的custom()方法创建一个HttpClientBuilder对象,并使用setRoutePlanner()方法为此对象设置上面创建的路由规划器。

//Setting the route planner to the HttpClientBuilder object
HttpClientBuilder clientBuilder = HttpClients.custom();

clientBuilder = clientBuilder.setRoutePlanner(routePlanner);

第 4 步 - 构建 CloseableHttpClient 对象

通过调用build()方法构建CloseableHttpClient对象。

//Building a CloseableHttpClient
CloseableHttpClient httpClient = clientBuilder.build();

第 5 步 - 创建 HttpGet 对象

通过实例化HttpGet类来创建 HTTP GET 请求。

//Creating an HttpGet object
HttpGet httpGet = new HttpGet("/");

第 6 步 - 执行请求

execute()方法的变体之一接受HttpHostHttpRequest对象并执行请求。使用此方法执行请求 -

//Executing the Get request
HttpResponse httpResponse = httpclient.execute(targetHost, httpGet); 

例子

以下示例演示如何通过代理向服务器发送 HTTP 请求。在此示例中,我们通过 localhost 向 google.com 发送 HTTP GET 请求。我们已经打印了响应的标题和响应的正文。

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.util.EntityUtils;

public class RequestViaProxyExample {

   public static void main(String args[]) throws Exception{
 
      //Creating an HttpHost object for proxy
      HttpHost proxyhost = new HttpHost("localhost");

      //Creating an HttpHost object for target
      HttpHost targethost = new HttpHost("google.com");
 
      //creating a RoutePlanner object
      HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyhost);

      //Setting the route planner to the HttpClientBuilder object
      HttpClientBuilder clientBuilder = HttpClients.custom();
      clientBuilder = clientBuilder.setRoutePlanner(routePlanner);

      //Building a CloseableHttpClient
      CloseableHttpClient httpclient = clientBuilder.build();

      //Creating an HttpGet object
      HttpGet httpget = new HttpGet("/");

      //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(targethost, httpget);

      //Printing the status line
      System.out.println(httpresponse.getStatusLine());

      //Printing all the headers of the response
      Header[] headers = httpresponse.getAllHeaders();
 
      for (int i = 0; i < headers.length; i++) {
         System.out.println(headers[i]);
      }
      
      //Printing the body of the response
      HttpEntity entity = httpresponse.getEntity();

      if (entity != null) {
         System.out.println(EntityUtils.toString(entity));
      }
   }
}

输出

执行时,上述程序生成以下输出 -

HTTP/1.1 200 OK
Date: Sun, 23 Dec 2018 10:21:47 GMT
Server: Apache/2.4.9 (Win64) PHP/5.5.13
Last-Modified: Tue, 24 Jun 2014 10:46:24 GMT
ETag: "2e-4fc92abc3c000"
Accept-Ranges: bytes
Content-Length: 46
Content-Type: text/html
<html><body><h1>It works!</h1></body></html>

Apache HttpClient - 代理身份验证

在本章中,我们将使用示例学习如何创建使用用户名和密码进行身份验证的 HttpRequest,并通过代理将其隧道传输到目标主机。

第 1 步 - 创建 CredentialsProvider 对象

CredentialsProvider 接口维护一个集合来保存用户登录凭据。您可以通过实例化 BasicCredentialsProvider 类(该接口的默认实现)来创建其对象。

CredentialsProvider credentialsPovider = new BasicCredentialsProvider();

第 2 步 - 设置凭据

您可以使用setCredentials()方法将所需的凭据设置到 CredentialsProvider 对象。此方法接受两个对象 -

  • AuthScope 对象- 指定详细信息(如主机名、端口号和身份验证方案名称)的身份验证范围。

  • 凭据对象- 指定凭据(用户名、密码)。使用setCredentials()方法为主机和代理设置凭据,如下所示。

credsProvider.setCredentials(new AuthScope("example.com", 80), new
   UsernamePasswordCredentials("user", "mypass"));
credsProvider.setCredentials(new AuthScope("localhost", 8000), new
   UsernamePasswordCredentials("abc", "passwd"));

第 3 步 - 创建 HttpClientBuilder 对象

使用HttpClients类的custom()方法创建HttpClientBuilder,如下所示 -

//Creating the HttpClientBuilder
HttpClientBuilder clientbuilder = HttpClients.custom();

第 4 步 - 设置 CredentialsProvider

您可以使用setDefaultCredentialsProvider()方法将 CredentialsProvider 对象设置为 HttpClientBuilder 对象。将先前创建的CredentialsProvider对象传递给此方法。

clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);

第 5 步 - 构建 CloseableHttpClient

使用build()方法构建CloseableHttpClient对象。

CloseableHttpClient httpclient = clientbuilder.build();

第 6 步 - 创建代理和目标主机

通过实例化HttpHost类来创建目标主机和代理主机。

//Creating the target and proxy hosts
HttpHost target = new HttpHost("example.com", 80, "http");
HttpHost proxy = new HttpHost("localhost", 8000, "http");

第 7 步 - 设置代理并构建 RequestConfig 对象

使用custom()方法创建RequestConfig.Builder对象。使用setProxy()方法将之前创建的 proxyHost 对象设置为RequestConfig.Builder。最后,使用build()方法构建RequestConfig对象。

RequestConfig.Builder reqconfigconbuilder= RequestConfig.custom();
reqconfigconbuilder = reqconfigconbuilder.setProxy(proxyHost);
RequestConfig config = reqconfigconbuilder.build();

步骤 8 - 创建 HttpGet 请求对象并为其设置配置对象。

通过实例化 HttpGet 类来创建HttpGet对象。使用setConfig()方法将上一步中创建的配置对象设置为此对象。

//Create the HttpGet request object
HttpGet httpGet = new HttpGet("/");

//Setting the config to the request
httpget.setConfig(config);

第 9 步 - 执行请求

通过将 HttpHost 对象(目标)和请求 (HttpGet) 作为参数传递给execute()方法来执行请求。

HttpResponse httpResponse = httpclient.execute(targetHost, httpget);

例子

以下示例演示如何使用用户名和密码通过代理执行 HTTP 请求。

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;

public class ProxyAuthenticationExample {
   public static void main(String[] args) throws Exception {

      //Creating the CredentialsProvider object
      CredentialsProvider credsProvider = new BasicCredentialsProvider();

      //Setting the credentials
      credsProvider.setCredentials(new AuthScope("example.com", 80), 
         new UsernamePasswordCredentials("user", "mypass"));
      credsProvider.setCredentials(new AuthScope("localhost", 8000), 
         new UsernamePasswordCredentials("abc", "passwd"));

      //Creating the HttpClientBuilder
      HttpClientBuilder clientbuilder = HttpClients.custom();

      //Setting the credentials
      clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);
      
      //Building the CloseableHttpClient object
      CloseableHttpClient httpclient = clientbuilder.build();


      //Create the target and proxy hosts
      HttpHost targetHost = new HttpHost("example.com", 80, "http");
      HttpHost proxyHost = new HttpHost("localhost", 8000, "http");

      //Setting the proxy
      RequestConfig.Builder reqconfigconbuilder= RequestConfig.custom();
      reqconfigconbuilder = reqconfigconbuilder.setProxy(proxyHost);
      RequestConfig config = reqconfigconbuilder.build();

      //Create the HttpGet request object
      HttpGet httpget = new HttpGet("/");

      //Setting the config to the request
      httpget.setConfig(config);
 
      //Printing the status line
      HttpResponse response = httpclient.execute(targetHost, httpget);
      System.out.println(response.getStatusLine());

   }
}

输出

执行时,上述程序生成以下输出 -

HTTP/1.1 200 OK

Apache HttpClient - 基于表单的登录

使用 HttpClient 库,您可以发送请求,或者通过传递参数登录表单。

请按照以下步骤登录表单。

第 1 步 - 创建 HttpClient 对象

HttpClients类的createDefault ()方法返回CloseableHttpClient类的对象,该类是 HttpClient 接口的基本实现。使用此方法创建一个 HttpClient 对象 -

CloseableHttpClient httpClient = HttpClients.createDefault();

第 2 步 - 创建 RequestBuilder 对象

RequestBuilder类用于通过向请求添加参数来构建请求。如果请求类型是 PUT 或 POST,它将参数作为 URL 编码实体添加到请求中

使用 post() 方法创建一个 RequestBuilder 对象(PO​​ST 类型)。

//Building the post request object
RequestBuilder reqbuilder = RequestBuilder.post();

步骤 3 - 将 Uri 和参数设置为 RequestBuilder。

使用 RequestBuilder 类的setUri()addParameter()方法将 URI 和参数设置为 RequestBuilder 对象。

//Set URI and parameters
RequestBuilder reqbuilder = reqbuilder.setUri("http://httpbin.org/post");
reqbuilder = reqbuilder1.addParameter("Name", "username").addParameter("password", "password");

第 4 步 - 构建 HttpUriRequest 对象

设置所需参数后,使用build()方法构建HttpUriRequest对象。

//Building the HttpUriRequest object
HttpUriRequest httppost = reqbuilder2.build();

第 5 步 - 执行请求

CloseableHttpClient 对象的execute 方法接受HttpUriRequest(接口)对象(即HttpGet、HttpPost、HttpPut、HttpHead 等)并返回响应对象。

通过将前面步骤中创建的 HttpUriRequest 传递给execute() 方法来执行它。

//Execute the request
HttpResponse httpresponse = httpclient.execute(httppost);

例子

以下示例演示如何通过发送登录凭据来登录表单。在这里,我们向表单发送了两个参数 -用户名和密码,并尝试打印消息实体和请求状态。

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;

public class FormLoginExample {
 
   public static void main(String args[]) throws Exception {

      //Creating CloseableHttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();
 
      //Creating the RequestBuilder object
      RequestBuilder reqbuilder = RequestBuilder.post();

      //Setting URI and parameters
      RequestBuilder reqbuilder1 = reqbuilder.setUri("http://httpbin.org/post");
      RequestBuilder reqbuilder2 = reqbuilder1.addParameter("Name", 
         "username").addParameter("password", "password");

      //Building the HttpUriRequest object
      HttpUriRequest httppost = reqbuilder2.build();

      //Executing the request
      HttpResponse httpresponse = httpclient.execute(httppost);

      //Printing the status and the contents of the response
      System.out.println(EntityUtils.toString(httpresponse.getEntity()));
      System.out.println(httpresponse.getStatusLine());
   }
}

输出

执行时,上述程序生成以下输出 -

{
   "args": {},
   "data": "",
   "files": {},
   "form": {
      "Name": "username",
      "password": "password"
   },
   "headers": {
      "Accept-Encoding": "gzip,deflate",
      "Connection": "close",
      "Content-Length": "31",
      "Content-Type": "application/x-www-form-urlencoded; charset = UTF-8",
      "Host": "httpbin.org",
      "User-Agent": "Apache-HttpClient/4.5.6 (Java/1.8.0_91)"
   },
   "json": null,
   "origin": "117.216.245.180",
   "url": "http://httpbin.org/post"
}
HTTP/1.1 200 OK

使用 Cookie 表单登录

如果您的表单存储 cookie,则不要创建默认的CloseableHttpClient对象。

通过实例化 BasicCookieStore 类来创建 CookieStore 对象。

//Creating a BasicCookieStore object
BasicCookieStore cookieStore = new BasicCookieStore();

使用HttpClients类的custom()方法创建 HttpClientBuilder

//Creating an HttpClientBuilder object
HttpClientBuilder clientbuilder = HttpClients.custom();

使用 setDefaultCookieStore() 方法将 cookie 存储设置到客户端构建器。

//Setting default cookie store to the client builder object
Clientbuilder = clientbuilder.setDefaultCookieStore(cookieStore); 

使用build()方法构建CloseableHttpClient对象。

//Building the CloseableHttpClient object
CloseableHttpClient httpclient = clientbuilder1.build();

通过传递执行请求来构建上面指定的HttpUriRequest对象。

如果页面存储了cookie,您传递的参数将被添加到cookie存储中。

您可以打印CookieStore对象的内容,您可以在其中看到您的参数(以及页面存储的先前参数)。

要打印 cookie,请使用getCookies()方法从CookieStore对象获取所有 cookie 。该方法返回一个List对象。使用迭代器打印列表对象内容,如下所示 -

//Printing the cookies
List list = cookieStore.getCookies();

System.out.println("list of cookies");
Iterator it = list.iterator();
if(it.hasNext()) {
   System.out.println(it.next());
}

Apache HttpClient - Cookie 管理

Cookie 是存储在客户端计算机上的文本文件,保留它们用于各种信息跟踪目的。

HttpClient 提供对 cookie 的支持,您可以创建和管理 cookie。

创建 cookie

按照下面给出的步骤使用 HttpClient 库创建 cookie。

第 1 步 - 创建 Cookiestore 对象

CookieStore接口表示 Cookie 对象抽象存储。您可以通过实例化BasicCookieStore类(该接口的默认实现)来创建 cookie 存储。

//Creating the CookieStore object
CookieStore cookieStore = new BasicCookieStore();

第 2 步 - 创建 ClientCookie 对象

ClientCookie除了具有cookie的功能外,还可以获取服务器中的原始cookie。您可以通过实例化BasicClientCookie类来创建客户端 cookie 。对于此类的构造函数,您需要传递您想要存储在该特定 cookie 中的键值对。

//Creating client cookie
BasicClientCookie clientCookie = new BasicClientCookie("name","Raju");

第 3 步 - 设置 cookie 的值

对于客户端 cookie,您可以使用相应的方法设置/删除路径、值、版本、到期日期、域、注释和属性。

Calendar myCal = new GregorianCalendar(2018, 9, 26);
Date expiryDate = myCal.getTime();
clientcookie.setExpiryDate(expiryDate);
clientcookie.setPath("/");
clientcookie.setSecure(true);
clientcookie.setValue("25");
clientcookie.setVersion(5);

第 4 步 - 将 cookie 添加到 cookie 存储区

您可以使用BasicCookieStore类的addCookie()方法将 cookie 添加到 cookie 存储中。

将所需的 cookie 添加到 Cookiestore

//Adding the created cookies to cookie store
cookiestore.addCookie(clientcookie);

例子

以下示例演示了如何创建 cookie 并将它们添加到 cookie 存储中。在这里,我们创建了一个 cookie 存储,通过设置域和路径值来创建一堆 cookie,并将这些添加到 cookie 存储中。

import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;

public class CookieHandlingExample {
   
   public static void main(String args[]) throws Exception{
      
      //Creating the CookieStore object
      CookieStore cookiestore = new BasicCookieStore();
 
      //Creating client cookies
      BasicClientCookie clientcookie1 = new BasicClientCookie("name","Raju");
      BasicClientCookie clientcookie2 = new BasicClientCookie("age","28");
      BasicClientCookie clientcookie3 = new BasicClientCookie("place","Hyderabad");

      //Setting domains and paths to the created cookies
      clientcookie1.setDomain(".sample.com");
      clientcookie2.setDomain(".sample.com");
      clientcookie3.setDomain(".sample.com");

      clientcookie1.setPath("/");
      clientcookie2.setPath("/");
      clientcookie3.setPath("/");
 
      //Adding the created cookies to cookie store
      cookiestore.addCookie(clientcookie1);
      cookiestore.addCookie(clientcookie2);
      cookiestore.addCookie(clientcookie3);
   }
}

检索 cookie

您可以使用asicCookieStore类的getCookies()方法将 cookie 添加到 cookie 存储中。此方法返回一个列表,其中包含 cookie 存储中的所有 cookie。

您可以使用迭代器打印 cookie 存储的内容,如下所示 -

//Retrieving the cookies
List list = cookieStore.getCookies();

//Creating an iterator to the obtained list
Iterator it = list.iterator();
while(it.hasNext()) {
   System.out.println(it.next());
}

例子

以下示例演示了如何从 cookie 存储中检索 cookie。在这里,我们将一堆 cookie 添加到 cookie 存储中并检索它们。

import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;

public class CookieHandlingExample {
 
   public static void main(String args[]) throws Exception{
      
      //Creating the CookieStore object
      CookieStore cookiestore = new BasicCookieStore();
      
      //Creating client cookies