restTemplate请求返回文件

2020-02-10  本文已影响0人  何佳阳

public void getShopDataExportNoReturn(JSONObject param, HttpServletResponse httpResponse) {

InputStream inputStream =null;

        OutputStream outputStream =null;

        try {

String url ="http://url?customUsername=" + param.getString("customUsername") +"&date=" + param.getString("date");

            HttpHeaders headers =new HttpHeaders();

            List mediaTypeList =new ArrayList<>();

            mediaTypeList.add(MediaType.APPLICATION_OCTET_STREAM);

            headers.setAccept(mediaTypeList);

            HttpEntity httpEntity =new HttpEntity(null, headers);

            ResponseEntity response =restTemplate.exchange(url, HttpMethod.GET, httpEntity, byte[].class);

            byte[] result = response.getBody();

            inputStream =new ByteArrayInputStream(result);

            outputStream = httpResponse.getOutputStream();

            int len =0;

            byte[] buf =new byte[1024];

            while ((len = inputStream.read(buf, 0, 1024)) != -1) {

outputStream.write(buf, 0, len);

            }

outputStream.flush();

        }catch (Exception ex) {

log.error("downloadFile error!", ex);

        }finally {

try {

if (inputStream !=null) {

inputStream.close();

                }

if (outputStream !=null) {

outputStream.close();

                }

}catch (Exception ex) {

}

}

    }

上一篇下一篇

猜你喜欢

热点阅读