在我的Springboot应用程序中,我使用RequestDispatcher
forward将请求和响应发送到远程服务。现在我需要得到response
和request
作为字符串来记录到数据库。request
和response
都包含JSON数据。
RequestDispatcher requestDispatcher = request.getRequestDispatcher(configAPI.getUserByPhoneUrl());
requestDispatcher.forward(request, response);
RequestDispatcher
将就地修改响应。因此,在forward()
函数之后,我无法从requestDispatcher.forward(request, response)
创建的响应中获取json。
@RequestMapping(value = "/getUserByPhone", method = {RequestMethod.GET}, produces = "application/json;charset=utf-8")
public void getUserbyIsdn(HttpServletRequest request, HttpServletResponse response) {
// Forward the request to the remote service
RequestDispatcher requestDispatcher = request.getRequestDispatcher(configAPI.getUserByPhoneUrl());
requestDispatcher.forward(request, response);
// response now has result from remote service
// TODO: print out json in response here
}
有没有关于如何获得响应作为json的想法?
我尝试使用HttpServletResponseWrapper
访问响应,但无法访问。使用HttpServletResponseWrapper
的示例代码:
HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request);
HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
// Forward the request to the remote service
request.getRequestDispatcher(configAPI.getUserByPhoneUrl()).forward(requestWrapper, responseWrapper);
但由于未设置ApplicationContext
请求,因此导致NullPointerException。
1条答案
按热度按时间0yg35tkg1#
经过一些尝试,我能够使用
ContentCachingRequestWrapper
和ContentCachingResponseWrapper
获得响应并请求json字符串。控制器现在变成这样:函数
addApiLog
: