java中使用okHttpClient下载网络图片到本地

本文介绍如何使用OkHttp库实现图片的下载功能,并提供了详细的代码示例。包括maven依赖的配置、图片URL处理及异常捕获等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

OkHttpClient官网: http://square.github.io/okhttp/

OkHttp GitHub地址:https://github.com/square/okhttp

首先导入maven依赖:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.6.0</version>
</dependency>

具体的代码实现:

public class OkHttpUtil {
    public static boolean downloadPic(OkHttpClient okHttpClient, String picUrl, String localFileName) {
        final File file = new File(localFileName);
        if (file.exists()) {
            file.delete();
        } else {
            try {
                FileUtils.forceMkdir(file.getParentFile());
                file.createNewFile();
            } catch (IOException e) {
                log.error("create file failed, file = " + file.getAbsolutePath(), e);
            }
        }

        InputStream is = null;
        FileOutputStream fos = null;

        try {
            picUrl = FormatUtils.getItemPicUrl(picUrl);
            Request request = new Request.Builder().url(picUrl).build();
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            byte[] buf = new byte[2048];
            int len = 0;
            is = response.body().byteStream();
            fos = new FileOutputStream(file);
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
            return true;
        } catch (IOException e) {
            log.error("download failed", e);
            return false;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                log.error("down loaded failed", e);
            }
        }

    }
(下篇将介绍将本地图片上传到阿里的OSS服务器中)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值