网络请求日志拦截器

class LoggingInterceptor implements Interceptor {
  @Override public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    KLog.i(String.format("Sending request %s on %s%n%s",
        request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    KLog.i(String.format("Received response for %s in %.1fms%n%s",
        response.request().url(), (t2 - t1) / 1e6d, response.headers()));

    return response;
  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了一种简单的方式来自定义请求拦截,可以通过实现HandlerInterceptor接口来实现。 HandlerInterceptor接口定义了三个方法,分别为preHandle()、postHandle()和afterCompletion(),它们分别对应请求处理前、请求处理后和请求处理完成后的处理逻辑。 下面是一个自定义请求拦截的示例代码: ```java @Component public class CustomInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 在请求处理之前进行调用(Controller方法调用之前) System.out.println("preHandle"); return true; // 如果返回false,请求将被中断 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 请求处理之后进行调用(但是在视图被渲染之前) System.out.println("postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 在整个请求处理完毕后进行调用,视图渲染完成后执行 System.out.println("afterCompletion"); } } ``` 在上述代码中,我们首先通过@Component注解将CustomInterceptor类标记为Spring Bean,然后实现了HandlerInterceptor接口,重写了preHandle()、postHandle()和afterCompletion()方法。 接下来,我们需要在Spring Boot应用中注册该拦截。可以通过实现WebMvcConfigurer接口,重写addInterceptors()方法来实现: ```java @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Autowired private CustomInterceptor customInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(customInterceptor); } } ``` 在上述代码中,我们首先通过@Configuration注解将WebMvcConfig类标记为Spring配置类,然后实现了WebMvcConfigurer接口,重写了addInterceptors()方法,将我们自定义的拦截注册到了拦截链中。 现在,我们就可以通过访问Spring Boot应用的任何一个Controller来测试该拦截了。在控制台上可以看到输出的日志信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值