Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abort large file upload with OkHttp?

Tags:

java

okhttp

I am using OkHttp 3.1.2. I've created file upload similar to the original recipe which is found here: https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/PostMultipart.java

I can't find example how to abort an upload of large file upon user request. I mean not how to get the user request but how to tell the OkHttp to stop sending data. So far the only solution that I can imagine is to use custom RequestBody, add an abort() method and override the writeTo() method like this:

public void abort() {
    aborted = true;
}

@Override
public void writeTo(BufferedSink sink) throws IOException {
    Source source = null;
    try {
        source = Okio.source(mFile);
        long transferred = 0;
        long read;

        while (!aborted && (read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
            transferred += read;
            sink.flush();
            mListener.transferredSoFar(transferred);

        }
    } finally {
        Util.closeQuietly(source);
    }
}

Is there any other way?

like image 447
Ognyan Avatar asked Nov 09 '22 18:11

Ognyan


1 Answers

It turns out it is quite easy:

Just hold reference to the Call object and cancel it when needed like this:

private Call mCall;


private void executeRequest (Request request) {
    mCall = mOkHttpClient.newCall(request);
    try {
        Response response = mCall.execute();
        ...
    } catch (IOException e) {
        if (!mCall.isCanceled()) {
            mLogger.error("Error uploading file: {}", e);
            uploadFailed(); // notify whoever is needed
        }
    }
}


public void abortUpload() {
    if (mCall != null) {
        mCall.cancel();
    }
}

Please note that when you cancel the Call while uploading an IOException will be thrown so you have to check in the catch if it is cancelled (as shown above) otherwise you will have false positive for error.

I think the same approach can be used for aborting download of large files.

like image 153
Ognyan Avatar answered Nov 14 '22 21:11

Ognyan