RestTemplate 拦截器

sou*_*ned 5 java spring interceptor resttemplate

我目前正在尝试合并 aHandlerInterceptorAdapter但它没有被注册并且将它与其他答案进行比较很困难,因为每个人都在使用不同的东西。而且我知道 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

拦截器: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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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());
  }

}

Run Code Online (Sandbox Code Playgroud)

“添加拦截器”确实被记录下来,所以我知道正在扫描配置。我只是无法获得任何拦截器逻辑来记录。

使用:

  • Spring Boot v1.5.15
  • 春季版本:4.3.18.RELEASE

use*_*900 5

RestTemplate 需要ClientHttpRequestInterceptor

setInterceptors(List<ClientHttpRequestInterceptor> interceptors)
Run Code Online (Sandbox Code Playgroud)

设置此访问器应使用的请求拦截器。

您可以使用Servlet Filter来“拦截”请求/响应,

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
Run Code Online (Sandbox Code Playgroud)

使用 servlet 过滤器来实现这一点。这里根本不涉及 Spring

但是你必须将 RestTemplate 更改为使用其他框架作为球衣

Jersey 提供了一个非常方便的实现,例如名为 LoggingFilter 的过滤器,它可以帮助记录各种传入和传出流量。