RestTemplate下载文件

来源:互联网 发布:sql union order by 编辑:程序博客网 时间:2024/05/01 14:24

http使用的是二进制进行传输,也就意味着无论我们输入是什么类型,最终都会被转为二进制进行传输,那么接受方如何解析呢,这便是http头的意义,我们将解析格式放在http头中,接受方接受到数据后回去根据头中我们定义的规则解析数据,包括数据格式,类型,编码方式,所以,要使用http 进行文件传输,头是必要的。restTemplate下载文件:

RestTemplate restTemplate = new RestTemplate();final String APPLICATION_PDF = "application/pdf";HttpHeaders headers = new HttpHeaders();InputStream inputStream = null;OutputStream outputStream = null;try {    List list = new ArrayList<>();    list.add(MediaType.valueOf(APPLICATION_PDF));    headers.setAccept(list);    ResponseEntity<byte[]> response = restTemplate.exchange(        url,        HttpMethod.GET,        new HttpEntity<byte[]>(headers),        byte[].class);    byte[] result = response.getBody();    inputStream = new ByteArrayInputStream(result);    File file = new File("/Users/feixiaobo/Desktop/test3.pdf");    if (!file.exists())    {        file.createNewFile();    }    outputStream = new FileOutputStream(file);    int len = 0;    byte[] buf = new byte[1024];    while ((len = inputStream.read(buf, 0, 1024)) != -1) {        outputStream.write(buf, 0, len);    }    outputStream.flush();}finally {    if(inputStream != null){        inputStream.close();    }    if(outputStream != null){        outputStream.close();    }}

0 0