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.
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
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:
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);