在Spring MVC控制器中代理HttpServletRequest的最简单方法

问题描述 投票:1回答:3

我正在使用spring-mvc构建REST服务,而我现在正在寻找的是一种从Spring MVC控制器内部向外部REST服务代理HTTP请求的方法。

我正在获取HttpServletRequest对象,并希望代理它尽可能少的更改。对我来说最重要的是保留传入请求的所有标头和属性。

@RequestMapping('/gateway/**')
def proxy(HttpServletRequest httpRequest) {
    ...
}

我只是尝试使用RestTemplate向外部资源发送另一个HTTP请求,但我找不到复制REQUEST ATTRIBUTES的方法(这在我的情况下非常重要)。

提前致谢!

java spring http spring-mvc
3个回答
2
投票

您可以使用spring rest模板方法exchange将请求代理到第三方服务。

@RequestMapping("/proxy")
@ResponseBody
public String proxy(@RequestBody String body, HttpMethod method, HttpServletRequest request, HttpServletResponse response) throws URISyntaxException {
    URI thirdPartyApi = new URI("http", null, "http://example.co", 8081, request.getRequestURI(), request.getQueryString(), null);

    ResponseEntity<String> resp =
        restTemplate.exchange(thirdPartyApi, method, new HttpEntity<String>(body), String.class);

    return resp.getBody();
}

What is the restTemplate.exchange() method for?


0
投票

我在Kotlin中编写了这个ProxyController方法,将所有传入的请求转发到远程服务(由主机和端口定义),如下所示:

@RequestMapping("/**")
fun proxy(requestEntity: RequestEntity<Any>, @RequestParam params: HashMap<String, String>): ResponseEntity<Any> {
    val remoteService = URI.create("http://remote.service")
    val uri = requestEntity.url.run {
        URI(scheme, userInfo, remoteService.host, remoteService.port, path, query, fragment)
    }

    val forward = RequestEntity(
        requestEntity.body, requestEntity.headers,
        requestEntity.method, uri
    )

    return restTemplate.exchange(forward)
}

请注意,远程服务的API应与此服务完全相同。


-1
投票

如果您考虑将API网关模式应用于微服务,请查看Netflix zuul,它是弹簧启动生态系统中的一个很好的替代方案。 here提供了一个很好的例子。

© www.soinside.com 2019 - 2024. All rights reserved.