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();
    }
}

猜你喜欢

转载自blog.csdn.net/silk_java/article/details/90692721
403