java - 下载进度

手机端应用比较多,浏览器端几乎没有需求,contentLength根据选用框架不同,写法会有不同,这里是okhttp的写法。

public static void copy(Response response, OutputStream os) throws IOException {
    InputStream is = response.body().byteStream();
    long total = response.body().contentLength();
    long cnt = 0;
    int len;
    byte[] buf = new byte[4096];
    while ((len = is.read(buf)) != -1) {
        os.write(buf, 0, len);
        cnt += len;
        int progress = (int) (cnt * 1.0f / total * 100);
        //TODO:进度回调
    }
    os.flush();
}

posted on 2019-10-15 22:12  疯狂的妞妞  阅读(648)  评论(0编辑  收藏  举报

导航