拦截器(interceptor)是那些有助于阻止或改变请求或响应的拦截器。协议拦截器通常作用于特定标头或一组相关标头。HttpClient库为拦截器提供支持。
请求拦截器
HttpRequestInterceptor
接口表示请求拦截器。此接口包含一个称为进程的方法,需要编写代码块来拦截请求。
在客户端,此方法在将请求发送到服务器之前验证/处理请求,并且在服务器端,此方法在评估请求的主体之前执行。
创建请求拦截器
可以按照以下步骤创建请求拦截器。
第1步 - 创建HttpRequestInterceptor
的对象
通过实现其抽象方法过程来创建HttpRequestInterceptor
接口的对象。
HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws
HttpException, IOException {
//Method implementation . . . . .
};
Java
第2步 - 实例化CloseableHttpClient对象
通过将以上创建的拦截器添加到它来构建自定义的CloseableHttpClient
对象,如下所示 -
//Creating a CloseableHttpClient object
CloseableHttpClient httpclient =
HttpClients.custom().addInterceptorFirst(requestInterceptor).build();
Java
使用此对象,可以照常执行请求执行。
示例
以下示例演示了请求拦截器的用法。在此示例中,创建了一个HTTP GET请求对象,并添加了三个标头:sample-header
,demoheader
和test-header
。
在拦截器processor()
方法中,验证发送请求的头部; 如果这些标头中的任何一个是sample-