在Spring RestTemplate和ResponseEntity中设置状态代码301或303

问题描述 投票:0回答:1

我创建了GET服务,以重定向到使用POST的网页。我正在尝试使用restTemplate,因为这样我可以发送请求服务的正文和标头,并且已经实现从服务中获取所需的信息。

但是,我需要重定向到具有POST服务的服务器,但是我不能,因为我不知道如何设置状态代码以重定向到另一台服务器。

这些是我正在使用的功能:

RequestEntity<Object> req = new RequestEntity<Object>(body, httpHeaders, HttpMethod.POST, url);

ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, req, String.class);
java spring resttemplate http-status-code-301
1个回答
0
投票

您可以这样做,因为http帖子在春季不会自动重定向。因此以下内容可能会有所帮助:

 public ResponseEntity<String> getData() {
 final RestTemplate restTemplate = new RestTemplate();
 String url = "http://localhost:8080/my-sample-post-url";
 final HttpComponentsClientHttpRequestFactory factory =
     new HttpComponentsClientHttpRequestFactory();
 final HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); //org.apache.httpcomponents 
 factory.setHttpClient(httpClient);
 restTemplate.setRequestFactory(factory);
 Map<String, String> params = new HashMap<String, String>();
 ResponseEntity<String> response = restTemplate.postForEntity(url,params,String.class);
 if(response.getStatusCode().equals(HttpStatus.OK)) {
   return new ResponseEntity<String>(HttpStatus.SEE_OTHER);
 }
 else {
    return new ResponseEntity(HttpStatus.NOT_FOUND); // for example only
 }

 }

注意:Lax RedirectStrategy实现会自动重定向所有HEAD,GET,POST和DELETE请求。此策略放宽了HTTP规范对POST方法的自动重定向的限制。 More here

© www.soinside.com 2019 - 2024. All rights reserved.