【代码块】OkHttp下载文件

/**
 * 下载文件
 *
 * @param url      文件网络路径
 * @param filePath 文件下载本地路径
 * @param fileName 文件名称(包含后缀)
 * @param callBack 回调
 */
public void okHttpDownloadFile(String url, String filePath, String fileName, final CallBackDownloadFile callBack) {
    final File incompleteFile = new File(filePath, fileName + ".ysy");
    final File completeFile = new File(filePath, fileName);
    Request request = new Request.Builder().url(url).build();
    new OkHttpClient().newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            callBack.onFailure(e);
        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            BufferedSink bufferedSink = null;
            try {
                Sink sink = Okio.sink(incompleteFile);
                bufferedSink = Okio.buffer(sink);
                bufferedSink.writeAll(response.body().source());
                bufferedSink.close();
                incompleteFile.renameTo(completeFile)
                callBack.onDownloadOk(response.body().string());
            } catch (Exception e) {
                e.printStackTrace();
                callBack.onDownloadError(e);
            } finally {
                if (bufferedSink != null) {
                    bufferedSink.close();
                }
            }
        }
    });
}
上一篇:okhttp像指定url发送图片并且获得返回值


下一篇:安卓开发论坛!自己动手实现OkHttp,震撼来袭免费下载!