简体   繁体   中英

How to abort large file upload with 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM