How to pause/resume downloading with okhttp in Android

前端 未结 2 1587
孤独总比滥情好
孤独总比滥情好 2021-02-05 21:43

I use okhttp library for download files in android. I download successfully. But something is wrong when I pause and resume download.

Response request = new Req         


        
相关标签:
2条回答
  • 2021-02-05 22:00
    val call = client.newCall(request)
    
    call.enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            listener.onFail(e)
        }
    
        override fun onResponse(call: Call, response: Response) {
            // write the stream to a file (downloading happening)
            val stream = response.body?.byteStream()
        }
    })
    
    // this will stop the downloading
    call.cancel()
    

    to resume use the "Range" header with your request and append the stream to already downloaded file.

    0 讨论(0)
  • 2021-02-05 22:19

    FIRST WAY

    I tried a lot of codes and finally I solved with BufferedSource source = responseBody.source(); source.skip(downloadedSize);

    Response request = new Request.Builder().url(url).build();
    ResponseBody responseBody = response.body();
    BufferedSource source = responseBody.source();
    
    if(isResume)
        source.skip(downloadedSize);
    
    File file = new File(filePath);
    BufferedInputStream input = new BufferedInputStream(responseBody.byteStream());
    OutputStream output;
    
    if (isResume) {
        output = new FileOutputStream(file, true);
    } else {
        output = new FileOutputStream(file, false);    
    }
    
    long currentDownloadedSize = 0;
    long currentTotalByteSize = responseBody.contentLength();
    byte[] data = new byte[1024];
    int count = 0;
    while ((count = input.read(data)) != -1) {
        currentDownloadedSize += count;
        output.write(data, 0, count);   
    }
    

    It worked successfully. I think I'm lucky :)

    SECOND WAY

    I added header for skip downloaded bytes and it worked.

    Request.Builder requestBuilder = new Request.Builder();
    if (isResume) {
        requestBuilder.addHeader("Range", "bytes=" + String.valueOf(downloadedSize) + "-");
    }
    Response request = requestBuilder.url(url).build();
    ResponseBody responseBody = response.body();
    BufferedSource source = responseBody.source();
    
    File file = new File(filePath);
    BufferedInputStream input = new BufferedInputStream(responseBody.byteStream());
    OutputStream output;
    
    if (isResume) {
        output = new FileOutputStream(file, true);
    } else {
        output = new FileOutputStream(file, false);    
    }
    
    long currentDownloadedSize = 0;
    long currentTotalByteSize = responseBody.contentLength();
    byte[] data = new byte[1024];
    int count = 0;
    while ((count = input.read(data)) != -1) {
        currentDownloadedSize += count;
        output.write(data, 0, count);   
    }
    
    0 讨论(0)
提交回复
热议问题