Example usage for com.squareup.okhttp Call cancel

List of usage examples for com.squareup.okhttp Call cancel

Introduction

In this page you can find the example usage for com.squareup.okhttp Call cancel.

Prototype

public void cancel() 

Source Link

Document

Cancels the request, if possible.

Usage

From source file:com.kubeiwu.easyandroid.easyhttp.core.retrofit.KOkHttpCall.java

License:Apache License

@Override
public void cancel() {
    canceled = true;/*from   w w w  .j a v a2  s  .co m*/
    com.squareup.okhttp.Call rawCall = this.rawCall;
    if (rawCall != null) {
        rawCall.cancel();
    }
}

From source file:com.mozillaonline.providers.downloads.DownloadThread.java

License:Apache License

/**
 * Executes the download in a separate thread
 *///from   w ww  . j  a  v a2s.  c om
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = Downloads.STATUS_UNKNOWN_ERROR;

    try {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
        wakeLock.acquire();

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "initiating download for " + mInfo.mUri);
        }

        boolean finished = false;
        while (!finished) {
            Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);

            Request.Builder requestBuilder = new Request.Builder();
            InnerState innerState = new InnerState();
            setupDestinationFile(state, innerState);
            addRequestHeaders(innerState, requestBuilder);
            requestBuilder.url(state.mRequestUri);

            Request request = requestBuilder.build();
            Call call = mOkHttpClient.newCall(request);
            try {
                executeDownload(innerState, state, call);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                call.cancel();
            }
        }

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = Downloads.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId + ": " + error.getMessage());
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
        // exceptions
        Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex);
        finalStatus = Downloads.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (mOkHttpClient != null) {
            mOkHttpClient.cancel(null);
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mGotData,
                state.mFilename, state.mNewUri, state.mMimeType);
        mInfo.mHasActiveThread = false;
    }
}

From source file:com.pangbo.android.thirdframworks.retrofit.OkHttpCall.java

License:Apache License

@Override
public void enqueue(final Callback<T> callback) {
    synchronized (this) {
        if (executed)
            throw new IllegalStateException("Already executed");
        executed = true;//  w  ww . ja  v a2  s  .  com
    }

    com.squareup.okhttp.Call rawCall;
    try {
        rawCall = createRawCall();
    } catch (Throwable t) {
        callback.onFailure(t);
        return;
    }
    if (canceled) {
        rawCall.cancel();
    }
    this.rawCall = rawCall;

    rawCall.enqueue(new com.squareup.okhttp.Callback() {
        private void callFailure(Throwable e) {
            try {
                callback.onFailure(e);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }

        private void callSuccess(Response<T> response) {
            try {
                callback.onResponse(response);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }

        @Override
        public void onFailure(Request request, IOException e) {
            callFailure(e);
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response rawResponse) {
            Response<T> response;
            try {
                response = parseResponse(rawResponse);
            } catch (Throwable e) {
                callFailure(e);
                return;
            }
            callSuccess(response);
        }
    });
}

From source file:com.pangbo.android.thirdframworks.retrofit.OkHttpCall.java

License:Apache License

public Response<T> execute() throws IOException {
    synchronized (this) {
        if (executed)
            throw new IllegalStateException("Already executed");
        executed = true;/*from  w ww . j  a  va2  s  . c  o  m*/
    }

    com.squareup.okhttp.Call rawCall = createRawCall();
    if (canceled) {
        rawCall.cancel();
    }
    this.rawCall = rawCall;

    return parseResponse(rawCall.execute());
}

From source file:com.pangbo.android.thirdframworks.retrofit.OkHttpCall.java

License:Apache License

public void cancel() {
    canceled = true;/*from   w  ww. ja va2s .  co m*/
    com.squareup.okhttp.Call rawCall = this.rawCall;
    if (rawCall != null) {
        rawCall.cancel();
    }
}

From source file:com.xing.api.CallSpec.java

License:Apache License

/**
 * Synchronously executes the request and returns it's response.
 *
 * @throws IOException If a problem occurred while talking to the server.
 * @throws RuntimeException If an unexpected error occurred during execution or while parsing response.
 *//*from   w ww  .  j a  v a  2 s. c om*/
public Response<RT, ET> execute() throws IOException {
    synchronized (this) {
        if (executed)
            throw stateError("Call already executed");
        executed = true;
    }

    Call rawCall = createRawCall();
    if (canceled)
        rawCall.cancel();
    this.rawCall = rawCall;

    return parseResponse(rawCall.execute());
}

From source file:com.xing.api.CallSpec.java

License:Apache License

/**
 * Asynchronously send the request and notify {@code callback} of its response or if an error
 * occurred talking to the server, creating the request, or processing the response.
 * <p>/*  ww  w . ja  v  a2s.  com*/
 * This method is <i>null-safe</i>, which means that there will be no failure or error propagated if
 * {@code callback} methods will throw an error.
 * <p>
 * Note that the {@code callback} will be dropped after the call execution.
 */
public void enqueue(final Callback<RT, ET> callback) {
    synchronized (this) {
        if (executed)
            throw stateError("Call already executed");
        executed = true;
    }

    Call rawCall;
    try {
        rawCall = createRawCall();
    } catch (Throwable t) {
        callback.onFailure(t);
        return;
    }
    if (canceled) {
        rawCall.cancel();
    }
    this.rawCall = rawCall;

    rawCall.enqueue(new com.squareup.okhttp.Callback() {
        private void callFailure(Throwable e) {
            try {
                callback.onFailure(e);
            } catch (Throwable t) {
                // TODO add some logging
            }
        }

        private void callSuccess(Response<RT, ET> response) {
            try {
                callback.onResponse(response);
            } catch (Throwable t) {
                // TODO add some logging
            }
        }

        @Override
        public void onFailure(Request request, IOException e) {
            callFailure(e);
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response rawResponse) {
            Response<RT, ET> response;
            try {
                response = parseResponse(rawResponse);
            } catch (Throwable e) {
                callFailure(e);
                return;
            }
            callSuccess(response);
        }
    });
}

From source file:com.xing.api.CallSpec.java

License:Apache License

/**
 * Cancel this call. An attempt will be made to cancel in-flight calls, and if the call has not yet been executed
 * it never will be./*from   w  w w.ja  v  a  2 s  .  c om*/
 */
public void cancel() {
    canceled = true;
    Call rawCall = this.rawCall;
    if (rawCall != null)
        rawCall.cancel();
}

From source file:me.lock8.Mzigo.java

License:Apache License

private boolean checkForDuplicatedRequest(final Request request) {

    final Call ongoingCall;
    if (request.method().equalsIgnoreCase("GET")
            && (ongoingCall = ongoingCallForPath(request.urlString())) != null) {

        if (duplicatedRequestPolicy == DUPLICATED_REQUEST_POLICY_CANCEL_ONGOING) {
            ongoingCall.cancel();
            return false;
        } else {/*from   w w  w . j  a va  2s .c om*/
            return true;
        }
    }
    return false;
}

From source file:microsoft.aspnet.signalr.client.http.android.AndroidOkHttpConnection.java

License:Open Source License

@Override
public HttpConnectionFuture execute(final Request request, final ResponseCallback responseCallback) {

    mLogger.log("Create new AsyncTask for HTTP Connection", LogLevel.Verbose);

    final HttpConnectionFuture future = new HttpConnectionFuture();

    com.squareup.okhttp.Request okHttpRequest = createRequest(request);

    final Call call = client.newCall(okHttpRequest);
    call.enqueue(new Callback() {
        @Override/*from   ww  w  .  j  a v  a2 s.  c o  m*/
        public void onFailure(com.squareup.okhttp.Request request, IOException e) {
            mLogger.log("Error executing request: " + e.getMessage(), LogLevel.Critical);
            future.triggerError(e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            mLogger.log("Request executed", LogLevel.Verbose);

            InputStream bodyStream = response.body().byteStream();
            Map<String, List<String>> headersMap = response.headers().toMultimap();
            try {
                responseCallback.onResponse(new StreamResponse(bodyStream, response.code(), headersMap));
                future.setResult(null);
            } catch (Exception e) {
                mLogger.log("Error calling onResponse: " + e.getMessage(), LogLevel.Critical);
                future.triggerError(e);
            }
        }
    });

    future.onCancelled(new Runnable() {
        @Override
        public void run() {
            call.cancel();
        }
    });

    return future;
}