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

2024-03-10

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

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

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

我只是尝试使用 RestTemplate 向外部资源发送另一个 HTTP 请求,但我找不到复制的方法请求属性(这对我来说非常重要)。

提前致谢!


我在 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 应该与此服务完全相同。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring MVC 控制器中代理 HttpServletRequest 最简单的方法 的相关文章

随机推荐