如何转发到外部url?

Vic*_*sky 4 spring spring-mvc forward spring-boot

我的基于 Spring 的应用程序在http://localhost下运行。另一个应用程序正在http://localhost:88下运行。我需要实现以下目标:当用户打开http://localhost/page时,内容为http://localhost:88/content时,应显示

我想我应该使用转发,如下所示:

@RequestMapping("/page")
public String handleUriPage() {
    return "forward:http://localhost:88/content";
}
Run Code Online (Sandbox Code Playgroud)

但似乎转发到外部 URL 不起作用。

我怎样才能用 Spring 实现这种行为?

Rob*_*zsi 5

首先,您指定要显示“ http://localhost:88/content ”的内容,但实际上在方法中转发到“ http://localhost:88 ”。

尽管如此,forward 仅适用于相对 URL(由同一应用程序的其他控制器提供服务),因此您应该使用“redirect:”。

转发完全发生在服务器端:Servlet 容器将相同的请求转发到目标 URL,因此地址栏中的 URL 不会改变。另一方面,重定向将导致服务器响应 302 并将 Location 标头设置为新的 URL,之后客户端浏览器将向其发出单独的请求,当然会更改地址栏中的 URL。

更新:为了返回外部页面的内容(因为它是内部页面的内容),我将编写一个单独的控制器方法来向 URL 发出请求并仅返回其内容。像下面这样:

@RequestMapping(value = "/external", produces = MediaType.TEXT_HTML_VALUE)
public void getExternalPage(@RequestParam("url") String url, HttpServletResponse response) throws IOException {
    HttpClient client = HttpClients.createDefault();
    HttpGet request = new HttpGet(url);
    HttpResponse response1 = client.execute(request);
    response.setContentType("text/html");
    ByteStreams.copy(response1.getEntity().getContent(), response.getOutputStream());
}
Run Code Online (Sandbox Code Playgroud)

当然,您有很多可能的解决方案。在这里,我使用 Apache Commons HttpClient 发出请求,并使用 Google 的 Guava 将响应从该请求复制到结果请求。之后,您的退货声明将更改为以下内容:

return "forward:/external?url=http%3A%2F%2Flocalhost%3A88%2Fcontent"
Run Code Online (Sandbox Code Playgroud)

请注意您需要如何对作为参数给出的 URL 进行编码。