Rest模板拦截器

RestTemplate Interceptor

我目前正在尝试合并一个 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);
  }
}

拦截器配置: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());
  }

}

"Adding interceptor" 确实被记录下来,所以我知道正在扫描配置。我只是无法获取任何拦截器逻辑来记录。

使用:

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

RestTemplate 需要 ClientHttpRequestInterceptor

setInterceptors(List<ClientHttpRequestInterceptor> interceptors)

Set the request interceptors that this accessor should use.

可以使用Servlet Filter到"intercept"requests/response,

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

implement this with a servlet filter. No Spring involved here at all

但是您必须将 RestTemplate 更改为使用其他框架 jersey

Jersey gives a very handy implementation of such as filter called LoggingFilter which can help in logging all kinds of incoming and outgoing traffic.

正如@WonChulHeo 指出的那样,您不能将 HandlerInterceptorAdapterRestTemplate 一起使用。只有 ClientHttpRequestInterceptor。目前尚不清楚您为什么需要 HandlerInterceptorAdapter - 我们只能看到您正在尝试记录请求拦截的事实。 ClientHttpRequestInterceptor 绝对能够做到同样甚至更多 - 请查看下面我的工作示例。

P.S。您的代码中有一个错误 - 您不能使用 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());
            }
        };
    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
}

HandlerInterceptorAdapter是服务端(即RestController)在服务端处理HTTP请求时拦截一些重要事件,与HTTP客户端(如RestTemplate)是什么无关使用过。

如果你想使用RestTemplate作为一个HTTP客户端,并且想拦截发送前的请求和接收后的响应,你必须使用ClientHttpRequestInterceptor

I’m trying to intercept requests and responses in a more flexible way than 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 体验与 Servlet 中的 Filter#doFilter() 非常相似。