okhttp 下载文件

今天,来说一个 我用的下载文件的方法,用的是okhttp下载方式

 a.加载依赖

implementation 'com.squareup.okhttp3:logging-interceptor:3.5.0'
implementation 'com.squareup.okhttp3:okhttp:3.6.0'

b.代码断

/**
 * Created by Jane on 2019/2/15.
 */
public class OkhttpDownloadFile {
    private final String TAG = "OkhttpDownloadFile";
    private String mSDCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    private static OkhttpDownloadFile okhttpDownloadFile;
    private static Context mContext;
    private static Handler handler;

    /**
     * 设置单例模式
     */
    public static OkhttpDownloadFile getInstance(Context context, Handler mHandle) {
        if (okhttpDownloadFile == null) {
            okhttpDownloadFile = new OkhttpDownloadFile();
        }
        handler = mHandle;
        return okhttpDownloadFile;
    }

    /**
     * 下载文件
     *
     * @param url      文件下载路径
     * @param fileName 文件名
     **/
    public void downloadFile(final String url, final String fileName) {
        //下载路径,如果路径无效了,可换成你的下载路径
        final long startTime = System.currentTimeMillis();
        Log.i(TAG, "startTime=" + startTime);
        Request request = new Request.Builder().url(url).build();
        new OkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                Log.e(TAG, "fail===cause==" + e.getCause().getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                Sink sink = null;
                BufferedSink bufferedSink = null;
                try {
                    File dest = new File(mSDCardPath, fileName);
                    sink = Okio.sink(dest);
                    bufferedSink = Okio.buffer(sink);
                    bufferedSink.writeAll(response.body().source());
                    bufferedSink.close();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("fileName", Constants.FILE_EXT_NAME);
                    jsonObject.put("filePath", mSDCardPath + "/" + Constants.FILE_EXT_NAME);
                    Message message = handler.obtainMessage();
                    message.what = 1;
                    message.obj = jsonObject.toString();
                    handler.sendMessage(message);
                    Log.i(TAG, "download success=" + mSDCardPath + "/" + Constants.FILE_EXT_NAME);
                    Log.i(TAG, "totalTime=" + (System.currentTimeMillis() - startTime));
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i(TAG, "download failed");
                } finally {
                    if (bufferedSink != null) {
                        bufferedSink.close();
                    }
                }
            }
        });
    }
}

其他就不多做介绍了,只要自己用着方便就行了啊哈

### 使用 OkHttp 进行文件下载 为了实现文件下载功能,可以利用 `OkHttpClient` 发起请求并处理响应中的字节流来保存文件。下面是一个完整的例子展示如何通过 OkHttp 下载文件: ```java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class FileDownloader { private static final OkHttpClient client = new OkHttpClient(); public void downloadFile(String fileUrl, String destinationFilePath) { try { Request request = new Request.Builder() .url(fileUrl) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Failed to fetch the file"); InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = response.body().byteStream(); File outputFile = new File(destinationFilePath); outputStream = new FileOutputStream(outputFile); byte[] buffer = new byte[4 * 1024]; // 缓冲区大小为4KB int read; while ((read = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, read); } outputStream.flush(); } finally { if (inputStream != null) inputStream.close(); if (outputStream != null) outputStream.close(); } } catch (IOException e) { System.err.println(e.getMessage()); } } } ``` 此代码片段展示了创建一个名为 `downloadFile` 的方法,该方法接收两个参数:要下载文件 URL 和目标路径[^2]。 #### 处理大文件时需要注意事项 当涉及到较大文件时,建议采用异步调用来避免阻塞主线程,并考虑加入进度条等功能提升用户体验。此外,在实际应用中还需要注意异常情况下的资源释放以及可能存在的并发问题[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值