Java 对接第三方接口返回的图片流下载保存
// 此处是某公司三方接口请求封装类,只需要关注返回的 HttpResponse 中的数据即可,HttpResponse中返回含有图片流 HttpResponse httpResponse = ArtemisHttpUtil.doPostStringImgArtemis(xxx); try { // 1. 计算文件保存的相对路径。如 "100002/1000009/f8c06dd111c043f0a1347286cc75224c.jpg" String relativePath = ImageUtils.calAscImgName(suffix, scCode, clCode); // 2. 文件的完整磁盘路径。如"D:/download/100002/1000009/f8c06dd111c043f0a1347286cc75224c.jpg" String imgFilePath = downPath + relativePath; // 3.文件地址校验 File file = new File(imgFilePath); File parentFolder = file.getParentFile(); if (!parentFolder.exists()) {// 当父文件夹不存在则创建文件夹 parentFolder.mkdirs(); } HttpEntity entity = httpResponse.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); //创建一个Buffer字符串 byte[] buffer = new byte[1024]; //每次读取的字符串长度,如果为-1,代表全部读取完毕 int len = 0; //使用一个输入流从buffer里把数据读取出来 while( (len=inputStream.read(buffer)) != -1 ){ //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度 outStream.write(buffer, 0, len); } //关闭输入流 inputStream.close(); //把outStream里的数据写入内存 byte[] bytes = outStream.toByteArray(); FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(bytes); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); }