RestController - Forward POST request to external URL
我正在寻找一种方法,如何转发已向
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | @RequestMapping("/**") public ResponseEntity mirrorRest(@RequestBody(required = false) String body, HttpMethod method, HttpServletRequest request, HttpServletResponse response) throws URISyntaxException { String requestUrl = request.getRequestURI(); URI uri = new URI("http", null, server, port, null, null, null); uri = UriComponentsBuilder.fromUri(uri) .path(requestUrl) .query(request.getQueryString()) .build(true).toUri(); HttpHeaders headers = new HttpHeaders(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); headers.set(headerName, request.getHeader(headerName)); } HttpEntity<String> httpEntity = new HttpEntity<>(body, headers); RestTemplate restTemplate = new RestTemplate(); try { return restTemplate.exchange(uri, method, httpEntity, String.class); } catch(HttpStatusCodeException e) { return ResponseEntity.status(e.getRawStatusCode()) .headers(e.getResponseHeaders()) .body(e.getResponseBodyAsString()); } } |
以上代码取自这个答案。
这更像是 HTTP 规范的问题,而不是 Spring,其中服务器应该返回 307 重定向状态,表明客户端应该使用相同的方法遵循重定向并发布数据。
这通常是在野外避免的,因为如果您符合 W3.org 规范,即在新位置重新执行请求之前应提示客户端,则存在很多误用和摩擦的可能性。 另一种方法是让您的 Spring 端点充当代理,对目标位置进行 POST 调用,而不是发出任何形式的重定向。
307 Temporary Redirect (since HTTP/1.1) In this occasion, the request should be repeated with another URI, but future requests can still use the original URI.2 In contrast to 303, the request method should not be changed when reissuing the original request. For instance, a POST request must be repeated using another POST request.