Download binary file from OKHTTP

前端 未结 6 1856
不知归路
不知归路 2020-11-22 11:53

I am using OKHTTP client for networking in my android application.

This example shows how to upload binary file. I would like to know how to get inputstream of binary

6条回答
  •  甜味超标
    2020-11-22 12:32

    This is how I use Okhttp + Okio libraries while publishing download progress after every chunk download:

    public static final int DOWNLOAD_CHUNK_SIZE = 2048; //Same as Okio Segment.SIZE
    
    try {
            Request request = new Request.Builder().url(uri.toString()).build();
    
            Response response = client.newCall(request).execute();
            ResponseBody body = response.body();
            long contentLength = body.contentLength();
            BufferedSource source = body.source();
    
            File file = new File(getDownloadPathFrom(uri));
            BufferedSink sink = Okio.buffer(Okio.sink(file));
    
            long totalRead = 0;
            long read = 0;
            while ((read = source.read(sink.buffer(), DOWNLOAD_CHUNK_SIZE)) != -1) {
                totalRead += read;
                int progress = (int) ((totalRead * 100) / contentLength);
                publishProgress(progress);
            }
            sink.writeAll(source);
            sink.flush();
            sink.close();
            publishProgress(FileInfo.FULL);
    } catch (IOException e) {
            publishProgress(FileInfo.CODE_DOWNLOAD_ERROR);
            Logger.reportException(e);
    }
    

提交回复
热议问题