我目前正在尝试合并HandlerInterceptorAdapter
,但尚未注册,将其与其他答案进行比较很困难,因为每个人都在使用不同的东西。而且我知道WebMvcConfigureAdapter已过时,对于项目范围,某些版本控制超出了我的控制范围,请参阅下面的使用规格。
有人可以提供一些与RestTemplate合并拦截器(不是ClientHttpRequestInterceptor)的指导。
主要:
@SpringBootApplication
@EnableRetry
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder applicationBuilder) {
return applicationBuilder.sources(Application.class);
}
@Bean
private RestTemplate restTemplate(){
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("redacted", 8080));
SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
simpleClientHttpRequestFactory.setProxy(proxy);
simpleClientHttpRequestFactory.setOutputStreaming(false);
RestTemplate template = new RestTemplate();
template.setErrorHandler(new MyResponseErrorHandler());
return template;
}
}
拦截器:com.example.foo.config.request.interceptor
@Component
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("INTERCEPTED");
return super.preHandle(request, response, handler);
}
}
InterceptorConfig:com.example.foo.config.request.interceptor
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
@Bean
MyInterceptor myInterceptor() {
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
System.out.println("Adding interceptor");
registry.addInterceptor(myInterceptor());
}
}
“添加拦截器”确实会被记录下来,所以我知道正在扫描配置。我只是无法记录任何拦截器逻辑。
使用:
答案 0 :(得分:1)
HandlerInterceptorAdapter
是适用于@Controller
或@RestController
的实现。不是RestTemplete
的实现。
要将其应用于RestTemplete
,您需要使用ClientHttpRequestInterceptor
。
例如。
@Component
public class CustomInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
// ...
}
}
@Configuation
public class RestTempleteConfig {
// ...
@Autowired
private CustomInterceptor customInterceptor;
@Bean
public RestTemplate restTemplate(){
RestTemplate template = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
template.add(customInterceptor);
return template;
}
}
答案 1 :(得分:1)
RestTemplate期望ClientHttpRequestInterceptor
setInterceptors(List<ClientHttpRequestInterceptor> interceptors)
设置该访问器应使用的请求拦截器。
您可以使用Servlet Filter来“拦截”请求/响应,
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response;
使用servlet过滤器来实现。春季完全没有参与
但是您必须将RestTemplate更改为使用其他框架作为jersey
Jersey提供了非常方便的实现,例如称为LoggingFilter的过滤器,可以帮助记录各种传入和传出的流量。
答案 2 :(得分:0)
如@WonChulHeo所述,您不能将HandlerInterceptorAdapter
与RestTemplate
一起使用。只有1个}}。目前尚不清楚您为什么需要确切的ClientHttpRequestInterceptor
-我们只能看到您正在尝试记录请求拦截的事实。 HandlerInterceptorAdapter
绝对可以做到甚至更多,请在下面查看我的工作示例。
P.S。您的代码中有错误-您无法对ClientHttpRequestInterceptor
方法使用private
访问权限-请检查您的@Bean
...
private RestTemplate restTemplate() {
@Slf4j
@RestController
@SpringBootApplication
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class)
.bannerMode(Banner.Mode.OFF)
.run(args);
}
@GetMapping("/users/{id}")
public User get(@PathVariable int id) {
log.info("[i] Controller: received request GET /users/{}", id);
return new User(id, "John Smith");
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder templateBuilder) {
ClientHttpRequestFactory requestFactory = new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
return templateBuilder
.interceptors((request, bytes, execution) -> {
URI uri = request.getURI();
HttpMethod method = request.getMethod();
log.info("[i] Interceptor: requested {} {}", method, uri);
log.info("[i] Interceptor: request headers {}", request.getHeaders());
ClientHttpRequest delegate = requestFactory.createRequest(uri, method);
request.getHeaders().forEach((header, values) -> delegate.getHeaders().put(header, values));
ClientHttpResponse response = delegate.execute();
log.info("[i] Interceptor: response status: {}", response.getStatusCode().name());
log.info("[i] Interceptor: response headers: {}", response.getHeaders());
String body = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset());
log.info("[i] Interceptor: response body: '{}'", body);
return response;
})
.rootUri("http://localhost:8080")
.build();
}
@Bean
ApplicationRunner run(RestTemplate restTemplate) {
return args -> {
ResponseEntity<User> response = restTemplate.getForEntity("/users/{id}", User.class, 1);
if (response.getStatusCode().is2xxSuccessful()) {
log.info("[i] User: {}", response.getBody());
} else {
log.error("[!] Error: {}", response.getStatusCode());
}
};
}
}
答案 3 :(得分:0)
HandlerInterceptorAdapter
用于服务器端(即RestController)在服务器处理HTTP请求时拦截一些重要事件,与所使用的HTTP客户端(例如RestTemplate
)无关。
如果要使用RestTemplate
作为HTTP客户端,并且想在发送之前拦截请求,而在接收之后立即拦截响应,则必须使用ClientHttpRequestInterceptor
。
我正在尝试以更灵活的方式拦截请求和响应 比ClientHttpRequestInterceptor。
从上面的评论中,您无法处理的实际用例是什么?我认为ClientHttpRequestInterceptor
已经足够灵活,可以实现任何复杂的逻辑来拦截请求和响应。由于您的问题没有提供有关如何进行拦截的任何信息,因此我只能举一个一般的示例来说明ClientHttpRequestInterceptor
可以提供的功能。
要将RestTemplate配置为使用拦截器:
RestTemplate rt = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors= new ArrayList<ClientHttpRequestInterceptor>();
inteceptors.add(new MyClientHttpRequestInterceptor());
ClientHttpRequestInterceptor看起来像:
public class MyClientHttpRequestInterceptor implements ClientHttpRequestInterceptor{
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
//The HTTP request and its body are intercepted here which you can log them or modify them. e.g.
System.out.println("Log the HTTP request header: " + request.getHeaders());
//Modify the HTTP request header....
request.getHeaders().add("foo", "fooValue");
//Throw exception if you do not want to send the HTTP request
//If it is at the end of the interceptor chain , call execution.execute() to confirm sending the HTTP request will return the response in ClientHttpResponse
//Otherwise, it will pass the request to the next interceptor in the chain to process
ClientHttpResponse response= execution.execute(request, body);
//The HTTP response is intercepted here which you can log them or modify them.e.g.
System.out.println("Log the HTTP response header: " + response.getHeaders());
//Modify the HTTP response header
response.getHeaders().add("bar", "barValue");
return response;
}
}
请注意,您还可以配置ClientHttpRequestInterceptor
链,该链可以将一些复杂的请求和响应拦截逻辑拆分为许多小的和可重复使用的ClientHttpRequestInterceptor
。它采用Chain of responsibility设计模式进行设计,其API经验与Filter#doFilter()
中的Servlet
非常相似。