2016-12-05 64 views
-2

我需要一個其響應爲HTML的休息結束點。但是我不想在我的項目中定義一個視圖,而是希望從該休息終點內發出的另一個請求轉發HTML響應。 例如,我的休息結束點向內部服務發出一個http請求並返回從該服務返回的HTML?可能嗎?有什麼想法嗎? 這裏是一個代碼示例Spring引導/ Spring MVC - 如何轉發來自另一個請求的響應

@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

所以你的問題是如何返回一個字符串? – zeroflagL

+0

如果我返回一個字符串,那麼spring會假定它的名稱和視圖出錯。我想返回HTML作爲響應的一部分 – Gowtham

+0

HTML文檔是一個字符串,不是嗎?如果一個方法用'@ ResponseBody'註釋,那麼Spring會返回字符串,而不是視圖。 – zeroflagL

回答

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); 
    } 
} 

如果您有更多的端點需要代理到另一個服務,您應該考慮使用eg Zuul作爲微代理。見例如this blog post解釋如何輕鬆創建這樣的代理。