restTemplate 403

使用Springboot RestTemplate组件去访问一个地址的时候,经常会遇到403的错误,这个时候,需要在请求头中加上user-agent属性来假装成浏览器欺骗服务器,如下所示:

public static void testGet() {
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<Resource> httpEntity = new HttpEntity<Resource>(headers);
RestTemplate template = new RestTemplate();
ResponseEntity<byte[]> response = template.exchange(IMG_URL, HttpMethod.GET,
httpEntity, byte[].class);
try {
List<String> cookies = response.getHeaders().get("Set-Cookie");
for (String cookie : cookies) {
System.out.println(cookie);
}
File file = File.createTempFile("ess-", "." + response.getHeaders().getContentType().getSubtype());
System.out.println(file.getName());
System.out.println(file.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(file);
fos.write(response.getBody());
fos.flush();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

转自https://blog.csdn.net/silk_java/article/details/90692721

————————————————
版权声明:本文为CSDN博主「micro_cloud_fly」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/silk_java/article/details/90692721

上一篇:DP的数组偏移


下一篇:HTTP请求的那些事儿