使用Spring restTemplate跟随302重定向?
RestTemplate restTemplate = new RestTemplate(); final MappingJackson2XmlHttpMessageConverter converter = new MappingJackson2XmlHttpMessageConverter(); final List supportedMediaTypes = new LinkedList(converter.getSupportedMediaTypes()); supportedMediaTypes.add(MediaType.ALL); converter.setSupportedMediaTypes(supportedMediaTypes); restTemplate.getMessageConverters().add(converter); ResponseEntity response = restTemplate.getForEntity(urlBase, MyDTO[].class); HttpHeaders headers = response.getHeaders(); URI location = headers.getLocation(); // Has my redirect URI response.getBody(); //Always null
我的印象是会自动跟踪302。 这个假设我不正确吗? 我现在需要选择这个位置并重新申请?
使用默认的ClientHttpRequestFactory
实现 – 这是SimpleClientHttpRequestFactory – 默认行为是遵循位置标头的URL(对于状态代码为3xx
响应) – 但仅当初始请求是GET
请求时。
详细信息可以在这个类中找到 – 搜索以下方法:
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { ... if ("GET".equals(httpMethod)) { connection.setInstanceFollowRedirects(true); }
这里是HttpURLConnection.setInstanceFollowRedirects
方法的相关文档注释:
设置此{@code HttpURLConnection}实例是否应自动遵循HTTP重定向(响应代码为3xx的请求)。
默认值来自followRedirects,默认为true。
使用CommonsClientHttpRequestFactory (使用下面的HttpClient v3 )时,您可以覆盖postProcessCommonsHttpMethod方法并设置为遵循重定向。
public class FollowRedirectsCommonsClientHttpRequestFactory extends CommonsClientHttpRequestFactory { @Override protected void postProcessCommonsHttpMethod(HttpMethodBase httpMethod) { httpMethod.setFollowRedirects(true); } }
然后,您可以像这样使用它(使用可选的,可能是预先配置的HttpClient实例),请求将在响应中跟随location
标头:
RestTemplate restTemplate = new RestTemplate( new FollowRedirectsCommonsClientHttpRequestFactory());