英文:
ContentCachingRequestWrapper only captures POST request with Content-Type:application/x-www-form-urlencoded
问题
我正尝试拦截所有传入的HTTP请求,并在我的Spring MVC(非Spring Boot)应用程序中处理这些请求附带的主体。为了实现这个“入站拦截器”,我正在使用Spring的HandlerInterceptor接口。一旦请求被拦截,我尝试以下方式检索主体:
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
Map<String, String[]> params = requestWrapper.getParameterMap();
byte[] body = requestWrapper.getContentAsByteArray();
参考这篇文章,以这种方式提取主体的局限性在于:
- 请求的Content-type必须是
x-www-form-urlencoded
。 - 请求的方法类型必须是
POST
。
对于我正在构建的应用程序,我无法强制执行这些约束,因为调用来自于我无法控制的异构来源。是否有一种方式可以覆盖这种行为,以允许提取不受默认支持的请求主体?或者,另外是否有另一种方法来执行这个任务?
附注:我正在对主体执行日志记录+一些自定义处理。因此像这个答案中提到的解决方案并不是太有帮助。
英文:
I am trying to intercept all incoming HTTP requests and process the body attached to these requests in my Spring MVC (not Spring Boot) app. To implement this "inbound-interceptor", I am using Spring's HandlerInterceptor interface. Once the request is intercepted, I am trying to retrieve the body as follows:
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
Map<String, String[]> params = requestWrapper.getParameterMap();
byte[] body = requestWrapper.getContentAsByteArray();
Referring to this article, the limitations of trying to extract the body this way are:
- Content-type of the request must be
x-www-form-urlencoded
- Method-type must be
POST
For the application I am building, I cannot enforce either of these constraints as the calls come from heterogeneous sources beyond my control. Is there some way to override this behavior to allow extraction of the body for requests not supported by default? Or, alternatively, is there another approach to performing this task?
P.S. I am performing logging + some custom processing on the body. So solutions such as the ones mentioned in this answer are not too helpful
答案1
得分: 1
你尝试过Logbook吗?https://github.com/zalando/logbook 与纯Spring一起使用。
它们的默认日志编写器看起来很有前途:https://github.com/zalando/logbook/blob/main/logbook-core/src/main/java/org/zalando/logbook/DefaultHttpLogWriter.java
你甚至可以扩展这个类以记录到所有你想要的日志记录器中。
除了日志记录,你甚至可以对请求进行完全不同的操作。
英文:
Have you tried Logbook? https://github.com/zalando/logbook Works with pure Spring.
Their Default Log Writer looks promising: https://github.com/zalando/logbook/blob/main/logbook-core/src/main/java/org/zalando/logbook/DefaultHttpLogWriter.java
And you may just want to extend this class to log to all Loggers you want.
You can even do something completely different with the request besides logging.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论