接收httpClient返回的文件二进制流

/**
     * 盖章文件Pdf下载
     * @Param url 请求下载地址
     * @Param accessToken token
     * */
    public HttpEntity pdfDownload(String url,String accessToken){
        HttpEntity entity = null;
        try{
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Content-Type","application/json;charset=UTF-8");
            httpGet.setHeader("Authorization","Bearer " + accessToken);
            HttpResponse response = httpClient.execute(httpGet);
            entity = response.getEntity();
        }catch (Exception e){
            e.printStackTrace();
        }
        return entity;
    }


    /**
     * 输出pdf
     * @Param entity 请求返回内容
     * @Param filePath 文件保存地址
     * */
    public long writeToPdf(HttpEntity entity,String filePath)throws Exception{
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        int size = 0;
        try{
            byte[] bytes = EntityUtils.toByteArray(entity);
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
            bis = new BufferedInputStream(byteInputStream);
            File file = new File(filePath);
            File path = file.getParentFile();
            if(!path.exists()){
                path.mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            byte[] buffer = new byte[1024];
            int length = bis.read(buffer);
            while(length != -1){
                bos.write(buffer,0,length);
                length = bis.read(buffer);
            }
            bos.flush();
            return bis.available();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                bos.close();
                fos.close();
                bis.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return size;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容