我想为我在网络服务上执行的每个请求设置两个拦截器。一种用于传出通信,一种用于响应。
我正在使用 ClientHttpRequestInterceptor
,它正在为传出工作。我设置如下:
//Rest template
RestTemplate tpl = api.getRestTemplate();
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add( new OutgoingRequestInterceptor() );
tpl.setInterceptors( interceptors );
但是,我想要类似这个拦截器的传入(响应)。我检查了 Spring Framework 源代码,但找不到任何相关内容。
有什么建议吗?
编辑:
可能是我糊涂了,或者我脑子里出了问题。我今天有点不舒服。
我的拦截器类中有以下代码:
@Override
public ClientHttpResponse intercept( HttpRequest request, byte[] bytes, ClientHttpRequestExecution requestExecution ) throws IOException
{
SLog.d( "intercepted!!"+request.getURI()+". Bytes: "+bytes );
try
{
Thread.sleep( 5000 );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
ClientHttpResponse response = requestExecution.execute( request, bytes );
SLog.d( "Response Headers: " + response.getHeaders());
return response;
}
问题:此代码是否适用于传出、传入或两者?
因为日志:request.getUri()
正在返回目标 URL。
然后,在 Response
对象上,我得到 WebService 发送的 header 。
所以我可以肯定的是,响应实际上是服务器响应。但是... getUri()
怎么样?它是在实际发送请求之前触发的,还是之后触发的?
最佳答案
好的。经过一些棘手的调试后,我明白了。
即使拦截器类称为 ClientHttpRequestInterceptor,它也会拦截两者。客户端请求,服务器响应。
这个拦截器类类似于一个包装器。
所以...
- 这个方法是整个请求的包装器。从请求之前和请求完成之后。
- 这部分代码在请求发送到 web 服务之前触发
- 这部分代码实际上与 WEBSERVICE 联系,因此它“暂停”在那里,直到它收到来自 web 服务的响应。
- 我们返回生成的响应。请注意,如果您使用作为 InputStream 的方法
response.getBody()
,您将使用它,因此之后它将为 null。我这么说是因为您不能直接记录它。你必须先镜像它。
关于java - 是否可以代理传入的请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20494098/