Gho*_*sty 5 java spring http spring-mvc
我正在使用 spring-mvc 构建 REST 服务,我现在正在寻找一种从 Spring MVC 控制器内部将 HTTP 请求代理到外部 REST 服务的方法。
我正在获取 HttpServletRequest 对象,并希望代理它进行尽可能少的更改。对我来说最重要的是保持传入请求的所有标头和属性原样。
@RequestMapping('/gateway/**')
def proxy(HttpServletRequest httpRequest) {
...
}
Run Code Online (Sandbox Code Playgroud)
我只是尝试使用 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)
}
Run Code Online (Sandbox Code Playgroud)
请注意,远程服务的 API 应该与此服务完全相同。
归档时间: |
|
查看次数: |
14387 次 |
最近记录: |