首页 > 其他 > 详细

restTemplate 403

时间:2021-06-11 14:31:10      阅读:27      评论:0      收藏:0      [点我收藏+]

使用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

restTemplate 403

原文:https://www.cnblogs.com/hai-/p/14874523.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!