如何在Spring的HttpServletResponse中返回Apache的HttpResponse?

时间:2013-12-13 17:45:31

标签: java spring servlets proxy httpresponse

我有一个使用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");
}

1 个答案:

答案 0 :(得分:3)

您可以为HttpMessageConverter类型编写自定义CloseableHttpResponse,这样您就可以返回@ResponseBody CloseableHttpResponse

有关详细信息,请参阅Mapping the response body with the @ResponseBody annotation