先上源码
@Override
public ClientHttpResponse execute(HttpRequest request,byte[]body)throws IOException {
if (this.iterator.hasNext()) {
ClientHttpRequestInterceptor nextInterceptor =this.iterator.next();
return nextInterceptor.intercept(request,body,this);
}
else {
HttpMethod method =request.getMethod();
Assert.state(method !=null,"No standard HTTP method");
ClientHttpRequest delegate =requestFactory.createRequest(request.getURI(),method);
request.getHeaders().forEach((key,value) ->delegate.getHeaders().addAll(key,value));
if (body.length >0) {
if (delegate instanceof StreamingHttpOutputMessage) {
StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage)delegate;
streamingOutputMessage.setBody(outputStream ->StreamUtils.copy(body,outputStream));
}
else {
StreamUtils.copy(body,delegate.getBody());
}
}
return delegate.execute();
}
}
当iterator.hasNext()为true时,execute()方法会遍历iterator来进行额外的设置 (也就是你所定义的拦截器中的操作),就像下面的例子一样:
@Bean
public ClientHttpRequestInterceptor requestInterceptor(AppParams params) {
return (request,body,execution) -> {
HttpHeaders headers =request.getHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add(HttpHeaders.COOKIE,"JSESSIONID=" +JSESSIONID);
return execution.execute(request,body);
};
}
当上面的方法执行到 return execution.execute(request,body)时将会再次进入最开始的execute()方法,继续判断iterator.hasNext()是否为true,若不为true,则进入else中的代码
网友评论