Use RestTemplate reported 301 Moved Permanently resolve

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Wu_Kunbo/article/details/102582036

Problem Description

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

(Get to all of China's provinces, cities). The results browser to directly access the following
The results of the browser to directly access
with RestTemplate direct access to this address, as follows

   		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<String> httpEntity = new HttpEntity<>(httpBody,httpHeaders);
        URI uri = URI.create(url+"?"+params);

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

        return resp.getBody();

The response body printout, as follows:
Here Insert Picture Description

solve

Check out the online information. The reason isRequest can not be automatically forwarded
To implement auto-forwarding, you need toRedirection policy settings to create HttpClient, Add the following code.

HttpComponentsClientHttpRequestFactory factory =
				   new HttpComponentsClientHttpRequestFactory();

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

factory.setHttpClient(httpClient);

restTemplate.setRequestFactory(factory);

Guess you like

Origin blog.csdn.net/Wu_Kunbo/article/details/102582036
301