我已经使用 spring mvc 框架构建了一个 Web 应用程序来发布 REST 服务。 例如:
@Controller
@RequestMapping("/movie")
public class MovieController {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public @ResponseBody Movie getMovie(@PathVariable String id, @RequestBody user) {
return dataProvider.getMovieById(user,id);
}
现在我需要部署我的应用程序,但我遇到了以下问题: 客户端无法直接访问应用程序所在的计算机(有防火墙)。因此,我需要在调用实际休息服务的代理机器(可由客户端访问)上的重定向层。
我尝试使用 RestTemplate 调用新电话: 例如:
@Controller
@RequestMapping("/movieProxy")
public class MovieProxyController {
private String address= "http://xxx.xxx.xxx.xxx:xx/MyApp";
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public @ResponseBody Movie getMovie(@PathVariable String id,@RequestBody user,final HttpServletResponse response,final HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
RestTemplate restTemplate = new RestTemplate();
return restTemplate.exchange( address+ request.getPathInfo(), request.getMethod(), new HttpEntity<T>(user, headers), Movie.class);
}
这没关系,但我需要重写 Controller 中的每个方法以使用 resttemplate。此外,这会导致代理机器上的冗余序列化/反序列化。
我尝试使用 restemplate 编写一个泛型函数,但没有成功:
@Controller
@RequestMapping("/movieProxy")
public class MovieProxyController {
private String address= "http://xxx.xxx.xxx.xxx:xx/MyApp";
@RequestMapping(value = "/**")
public ? redirect(final HttpServletResponse response,final HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
RestTemplate restTemplate = new RestTemplate();
return restTemplate.exchange( address+ request.getPathInfo(), request.getMethod(), ? , ?);
}
我找不到适用于请求和响应对象的 resttemplate 方法。
我还尝试了 Spring 重定向和转发。但是重定向不会更改请求的客户端 IP 地址,所以我认为在这种情况下它是无用的。我也无法转发到另一个 URL。
有没有更合适的方法来实现这一点? 提前致谢。
最佳答案
您可以使用此镜像/代理所有请求:
private String server = "localhost";
private int port = 8080;
@RequestMapping("/**")
@ResponseBody
public String mirrorRest(@RequestBody String body, HttpMethod method, HttpServletRequest request) throws URISyntaxException
{
URI uri = new URI("http", null, server, port, request.getRequestURI(), request.getQueryString(), null);
ResponseEntity<String> responseEntity =
restTemplate.exchange(uri, method, new HttpEntity<String>(body), String.class);
return responseEntity.getBody();
}
这不会反射(reflect)任何标题。
关于java - spring mvc 休息服务重定向/转发/代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14726082/