在Spring MVC控制器中代理HttpServletRequest的最简单方法 [英] The easiest way to proxy HttpServletRequest in Spring MVC controller

查看:405
本文介绍了在Spring MVC控制器中代理HttpServletRequest的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building REST services using spring-mvc and what I'm looking for now is a way to proxy HTTP request to external REST service from inside Spring MVC controller.

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

I'm getting HttpServletRequest object and want to proxy it making as few changes as possible. What is essential for me is keeping all the headers and attributes of incoming request as they are.

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

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

I was trying simply to send another HTTP request to external resource using RestTemplate but I failed to find a way to copy REQUEST ATTRIBUTES (which is very important in my case).

提前谢谢!

推荐答案

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

I wrote this ProxyController method in Kotlin to forward all incoming requests to remote service (defined by host and port) as follows:

@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应该与此服务完全相同.

Note that the API of the remote service should be exactly same as this service.

这篇关于在Spring MVC控制器中代理HttpServletRequest的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆