Spring boot / Spring MVC - 如何转发来自另一个请求的响应

时间:2016-12-05 20:14:45

标签: spring spring-mvc spring-boot

我需要一个响应为HTML的休息终点。但是,我想在我的项目中定义的视图中转发HTML响应,而不是在该休息终点内发出的另一个请求。 例如,我的rest端点向内部服务发出http请求并返回从该服务返回的HTML?可能吗?有什么想法吗? 这是一个代码示例

@RequestMapping("/test")
public String testMe(Model model, @RequestParam("param1") String param1, @RequestParam("param2") String param2)
{
    //Make a Http call to an internal service and return the response from that call
    return "<RESPONSE_FROM_THAT_CALL>";
}

我想从内部服务

返回HTML响应

1 个答案:

答案 0 :(得分:1)

您可以使用RestTemplate从其他服务中获取结果,然后将其作为String返回:

@Controller
public class MyController {

    private RestTemplate restTemplate = new RestTemplate();

    @ResponseBody
    @RequestMapping("/test")
    public String testMe(Model model, @RequestParam("param1") String param1, @RequestParam("param2") String param2) {
        URI uri = UriComponentsBuilder.fromHttpUrl("http://www.example.com");
            .queryParam("param1", param1)
            .queryParam("param2", param2)
            .build()
            .toUri());
        return restTemplate.getForObject(uri, String.class);
    }
}

如果您要将更多端点代理到其他服务,则应考虑使用例如Zuul作为微代理。参见例如this blog post解释了如何轻松创建此类代理。