我正在使用Apache的HttpClient为受保护的api服务编写一个java客户端 . 我想知道是否可以自动为每个请求添加动态标头,而不必在每个HttpGet或HttpPost实例上添加标头 . 标头需要获取请求URL和请求方法(GET或POST),因为这个要求我不能简单地在构建HttpClient时将其添加到默认请求头 . 谢谢
使用自定义请求拦截器
CloseableHttpClient client = CachingHttpClients.custom() .addInterceptorLast((HttpRequestInterceptor) (request, context) -> { String method = request.getRequestLine().getMethod(); String requestUri = request.getRequestLine().getUri(); request.addHeader("x-my-header", doSomethingClever(method, requestUri)); }) .build();
1 回答
使用自定义请求拦截器