发布于 

RestTemplate请求403解决记录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class test {

public void test(){
HttpHeaders headers = new HttpHeaders();
// 添加模拟谷歌浏览器头信息
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
Map<String, String> params = new HashMap<>(2);
params.put("TYPE", "N");
params.put("WEEK", "y");
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString("http://timor.tech/api/holiday/year/");
for (Map.Entry<String, String> entry : params.entrySet()) {
uriComponentsBuilder.queryParam(entry.getKey(), entry.getValue());
}
URI uri = uriComponentsBuilder.build().encode().toUri();
ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET,httpEntity,String.class);
// 数据解析
if (HttpStatus.OK == response.getStatusCode()) {
System.out.println(JSONObject.parseObject(response.getBody()));
}
}

}

本站由 @binvv 使用 Stellar 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。