【问题标题】:Set status code 301 or 303 in Spring RestTemplate and ResponseEntity在 Spring RestTemplate 和 ResponseEntity 中设置状态码 301 或 303
【发布时间】:2020-06-24 15:24:42
【问题描述】:

我创建了一个 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】:

你可以做这样的事情,因为 http post 在春天不会自动重定向。所以以下可能会有所帮助:

 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
 }

 }

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

【讨论】:

    猜你喜欢
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 2016-01-16
    • 1970-01-01
    相关资源
    最近更新 更多