java使用OKhttp实现下载图片功能简单实例

  1. 添加依赖:

            <dependency>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
                <version>3.6.0</version>
            </dependency>
    
  2. 发送OKhttp请求,我是调用第三方接口返回图片,之后再次解析图片:

    public static void getImage(String url, String filePath){
            InputStream inputStream = null;
            FileOutputStream fileOutputStream = null;
            String fileParam = filePath + "_barcode";
            System.out.println("get请求路径:" + url + fileParam);
            try {
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                Request request = new Request.Builder()
                        .url(url+fileParam)
                        .method("GET", null)
                        .addHeader("Accept", "*/*")
                        .addHeader("Content-Type", "image/jpeg")
                        .build();
                ResponseBody body = client.newCall(request).execute().body();
    //            inputStream = body.byteStream();
                byte[] bytes = body.bytes();
                String result = ImageBase64Utils.bytesToBase64(bytes);
                //输出图片的路径
                String fileOutPath = filePath.replaceAll("sdpc","jpeg");
                ImageBase64Utils.base64ToImageFile(result, fileOutPath);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    
  3. 封装公共工具类:

    package com.insightzen.management.utils;
    
    import java.io.*;
    
    /**
     * @author Mayz
     * @description
     * @date 2021/7/22 13:42
     */
    public class ImageBase64Utils {
    
    
        public static String bytesToBase64(byte[] bytes) {
            return org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);// 返回Base64编码过的字节数组字符串
        }
    
        /**
         * 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
         *
         * @param path 图片路径
         * @return base64字符串
         */
        public static String imageToBase64(String path) throws IOException {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
            byte[] data = null;
            // 读取图片字节数组
            InputStream in = null;
            try {
                in = new FileInputStream(path);
                data = new byte[in.available()];
                in.read(data);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return org.apache.commons.codec.binary.Base64.encodeBase64String(data);// 返回Base64编码过的字节数组字符串
        }
    
        /**
         * 处理Base64解码并写图片到指定位置
         *
         * @param base64 图片Base64数据
         * @param path   图片保存路径
         * @return
         */
        public static boolean base64ToImageFile(String base64, String path) throws IOException {// 对字节数组字符串进行Base64解码并生成图片
            // 生成jpeg图片
            try {
                OutputStream out = new FileOutputStream(path);
                return base64ToImageOutput(base64, out);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            return false;
        }
    
        /**
         * 处理Base64解码并输出流
         *
         * @param base64
         * @param out
         * @return
         */
        public static boolean base64ToImageOutput(String base64, OutputStream out) throws IOException {
            if (base64 == null) { // 图像数据为空
                return false;
            }
            try {
                // Base64解码
                byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(base64);
                for (int i = 0; i < bytes.length; ++i) {
                    if (bytes[i] < 0) {// 调整异常数据
                        bytes[i] += 256;
                    }
                }
                // 生成jpeg图片
                out.write(bytes);
                out.flush();
                return true;
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
  4. 查看指定的输出目录是否生成图片以及图片是否可以正常显示;

  5. 以前都是自己写httpclient请求的,偶然间发现postman可以自动生成OKhttp代码,省得自己写咯!!!嘻嘻!!!

  6. happy ending!!!

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mayz梅子子子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值