我有一个使用 Spring 的端点:
@RequestMapping(value = {"/hello"}, method = RequestMethod.GET)
@ResponseBody
public String getContent(@RequestParam(value = "url", required = true) String url)
我希望它返回与我向 url
发送 GET 时得到的完全相同的响应。我正在使用 Apache 库执行 GET,它返回一个 CloseableHttpResponse
。如何返回此响应作为我的端点的响应?我当前的代码复制了此响应,这不是我想要的。我想直接返回CloseableHttpResponse
。我想这样做的原因是因为有些网站拥有非常庞大的数据,我想避免必须复制这些数据。
@RequestMapping(value = {"/hello"}, method = RequestMethod.GET)
@ResponseBody
public String getContent(@RequestParam(value = "url", required = true) String url, HttpServletResponse response)
CloseableHttpResponse httpResponse = useApacheLibraryAndSendGetToUrl(url);
for (Header header : httpResponse.getAllHeaders()) {
response.addHeader(header.getName(), header.getValue());
}
response.setStatus(httpResponse.getStatusLine().getStatusCode());
return EntityUtils.toString(entity, "UTF-8");
}
最佳答案
您可以为 CloseableHttpResponse
类型编写一个自定义 HttpMessageConverter
,这样您就可以简单地返回 @ResponseBody CloseableHttpResponse
。
参见Mapping the response body with the @ResponseBody annotation了解详情。
关于java - 如何在 Spring 的 HttpServletResponse 中返回 Apache 的 HttpResponse?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20572788/