spring mvc rest service redirect / forward / proxy

后端 未结 6 1485
南旧
南旧 2020-11-27 12:02

I have build a web application using spring mvc framework to publish REST services. For example:

@Controller
@RequestMapping(\"/movie\")
public class MovieCo         


        
6条回答
  •  青春惊慌失措
    2020-11-27 12:29

    Here's my modified version of the original answer, which differs in four points:

    1. It does not make the request body mandatory, and as such does not let GET requests fail.
    2. It copies all headers present in the original request. If you are using another proxy/web server, this can cause issues due to content length/gzip compression. Limit the headers to the ones you really need.
    3. It does not reencode the query params or the path. We expect them to be encoded anyway. Note that other parts of your URL might also be encoded. If that is the case for you, leverage the full potential of UriComponentsBuilder.
    4. It does return error codes from the server properly.

    @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 headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headers.set(headerName, request.getHeader(headerName));
        }
    
        HttpEntity 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());
        }
    }
    

提交回复
热议问题