使用Spring restTemplate跟随302重定向? [英] Follow 302 redirect using Spring restTemplate?
问题描述
RestTemplate restTemplate = new RestTemplate();
final MappingJackson2XmlHttpMessageConverter converter = new MappingJackson2XmlHttpMessageConverter();
final List<MediaType> supportedMediaTypes = new LinkedList<MediaType>(converter.getSupportedMediaTypes());
supportedMediaTypes.add(MediaType.ALL);
converter.setSupportedMediaTypes(supportedMediaTypes);
restTemplate.getMessageConverters().add(converter);
ResponseEntity<MyDTO[]> response = restTemplate.getForEntity(urlBase, MyDTO[].class);
HttpHeaders headers = response.getHeaders();
URI location = headers.getLocation(); // Has my redirect URI
response.getBody(); //Always null
我的印象是会自动跟踪302。这个假设我不正确吗?我现在需要选择这个位置并重新请求?
I was under the impression that a 302 would automatically be followed. Am I incorrect in this assumption? I now need to pick off this location and re-request?
推荐答案
使用默认 ClientHttpRequestFactory
实现 - 这是 SimpleClientHttpRequestFactory - 默认行为是遵循位置标题的URL(对于状态代码 3xx
) - 但仅当初始请求是 GET
请求时。
Using the default ClientHttpRequestFactory
implementation - which is the SimpleClientHttpRequestFactory - the default behaviour is to follow the URL of the location header (for responses with status codes 3xx
) - but only if the initial request was a GET
request.
详细信息可在此课程中找到 - 搜索以下方法:
Details can be found in this class - searching for the following method:
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
...
if ("GET".equals(httpMethod)) {
connection.setInstanceFollowRedirects(true);
}
此处的相关文档评论HttpURLConnection.setInstanceFollowRedirects
方法:
设置HTTP重定向(响应代码为3xx的请求)是否应自动跟随
这个{@code HttpURLConnection}
实例。
默认值来自followRedirects,默认为true。
Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this {@code HttpURLConnection} instance.
The default value comes from followRedirects, which defaults to true.
这篇关于使用Spring restTemplate跟随302重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!