使用RestTemplate报301 Moved Permanently解决

问题描述

今天想尝试使用今日头条的城市接口
https://www.toutiao.com/stream/widget/local_weather/city/

(获取到中国所有的省、城市)。浏览器直接访问的结果如下
使用RestTemplate报301 Moved Permanently解决_第1张图片
用RestTemplate直接访问这个地址,代码如下

   		RestTemplate restTemplate = new RestTemplate();
   		//消息头的ContentType
        MediaType type = MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        //请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(type);
        //请求体
        String httpBody = null;

        HttpEntity httpEntity = new HttpEntity<>(httpBody,httpHeaders);
        URI uri = URI.create(url+"?"+params);

        //发起请求
        ResponseEntity resp = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class);

        return resp.getBody();

对响应体进行打印输出,结果如下:
使用RestTemplate报301 Moved Permanently解决_第2张图片

解决

查阅了网上的资料。原因是请求不能自动转发
要实现自动转发,则需创建HttpClient设置重定向策略,加上以下代码即可。

HttpComponentsClientHttpRequestFactory factory =
				   new HttpComponentsClientHttpRequestFactory();

HttpClient httpClient =
				   HttpClientBuilder.create()
				  .setRedirectStrategy(new LaxRedirectStrategy())
				  .build();

factory.setHttpClient(httpClient);

restTemplate.setRequestFactory(factory);

你可能感兴趣的:(Rest)