[英]Set status code 301 or 303 in Spring RestTemplate and ResponseEntity
I've created a GET service to redirect to a webpage that uses POST.我创建了一个 GET 服务来重定向到使用 POST 的网页。 I'm trying to use
restTemplate
because with this I can send the body and header that request the service and I've achieved to get the information that a I need from the service.我正在尝试使用
restTemplate
因为这样我可以发送请求服务的正文和标题,并且我已经实现了从服务中获取我需要的信息。
However, I need to redirect to the server that has the POST service, but I couldn't, because I don't know how can a set the status code which I redirect to another server.但是,我需要重定向到具有 POST 服务的服务器,但我不能,因为我不知道如何设置重定向到另一台服务器的状态代码。
These are the functions that I'm using:这些是我正在使用的功能:
RequestEntity<Object> req = new RequestEntity<Object>(body, httpHeaders, HttpMethod.POST, url);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, req, String.class);
You could do something like this as http post are not redirected automatically in spring.你可以做这样的事情,因为 http 帖子在 spring 中不会自动重定向。 So the following might help:
因此,以下内容可能会有所帮助:
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
}
}
Note: Lax RedirectStrategy implementation that automatically redirects all HEAD, GET, POST, and DELETE requests.
注意:自动重定向所有 HEAD、GET、POST 和 DELETE 请求的 Lax RedirectStrategy 实现。 This strategy relaxes restrictions on automatic redirection of POST methods imposed by the HTTP specification.
此策略放宽了 HTTP 规范对 POST 方法的自动重定向的限制。 More here
更多在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.