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