List of usage examples for com.squareup.okhttp Call cancel
public void cancel()
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void canceledBeforeExecute() throws Exception { Call call = client.newCall(new Request.Builder().url(server.getUrl("/a")).build()); call.cancel(); try {//from w w w. j av a2 s . c o m FiberOkHttpUtil.executeInFiber(call); fail(); } catch (IOException expected) { } assertEquals(0, server.getRequestCount()); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void cancelBeforeBodyIsRead() throws Exception { server.enqueue(new MockResponse().setBody("def").throttleBody(1, 750, TimeUnit.MILLISECONDS)); final Call call = client.newCall(new Request.Builder().url(server.getUrl("/a")).build()); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Response> result = executor.submit(new Callable<Response>() { @Override//from w w w.j av a 2s . co m public Response call() throws Exception { return FiberOkHttpUtil.executeInFiber(call); } }); Thread.sleep(100); // wait for it to go in flight. call.cancel(); try { result.get().body().bytes(); fail(); } catch (IOException expected) { } assertEquals(1, server.getRequestCount()); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void canceledBeforeResponseReadSignalsOnFailure() throws Exception { Request requestA = new Request.Builder().url(server.getUrl("/a")).tag("request A").build(); final Call call = client.newCall(requestA); server.get().setDispatcher(new Dispatcher() { @Override/*from w w w .j a v a 2 s .c om*/ public MockResponse dispatch(RecordedRequest request) { call.cancel(); return new MockResponse().setBody("A"); } }); call.enqueue(callback); assertEquals("/a", server.takeRequest().getPath()); callback.await(requestA.url()).assertFailure("Canceled", "stream was reset: CANCEL", "Socket closed"); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
/** * There's a race condition where the cancel may apply after the stream has already been * processed./*from w ww.j av a 2 s.c o m*/ */ @Test public void canceledAfterResponseIsDeliveredBreaksStreamButSignalsOnce() throws Exception { server.enqueue(new MockResponse().setBody("A")); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<String> bodyRef = new AtomicReference<>(); final AtomicBoolean failureRef = new AtomicBoolean(); Request request = new Request.Builder().url(server.getUrl("/a")).tag("request A").build(); final Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { failureRef.set(true); latch.countDown(); } @Override public void onResponse(Response response) throws IOException { call.cancel(); try { bodyRef.set(response.body().string()); } catch (IOException e) { // It is ok if this broke the stream. bodyRef.set("A"); throw e; // We expect to not loop into onFailure in this case. } finally { latch.countDown(); } } }); latch.await(); assertEquals("A", bodyRef.get()); assertFalse(failureRef.get()); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void cancelWithInterceptor() throws Exception { client.interceptors().add(new Interceptor() { @Override/*from w w w .java2 s .c om*/ public Response intercept(Chain chain) throws IOException { chain.proceed(chain.request()); throw new AssertionError(); // We expect an exception. } }); Call call = client.newCall(new Request.Builder().url(server.getUrl("/a")).build()); call.cancel(); try { call.execute(); fail(); } catch (IOException expected) { } assertEquals(0, server.getRequestCount()); }
From source file:com.anony.okhttp.sample.CancelCall.java
License:Apache License
public void run() throws Exception { Request request = new Request.Builder().url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay. .build();//from w w w.ja v a 2 s . c o m final long startNanos = System.nanoTime(); final Call call = client.newCall(request); // Schedule a job to cancel the call in 1 second. executor.schedule(new Runnable() { @Override public void run() { System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f); call.cancel(); System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f); } }, 1, TimeUnit.SECONDS); try { System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f); Response response = call.execute(); System.out.printf("%.2f Call was expected to fail, but completed: %s%n", (System.nanoTime() - startNanos) / 1e9f, response); } catch (IOException e) { System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e); } }
From source file:com.facebook.imagepipeline.backends.okhttp.OkHttpNetworkFetcher.java
License:Open Source License
@Override public void fetch(final OkHttpNetworkFetchState fetchState, final Callback callback) { fetchState.submitTime = SystemClock.elapsedRealtime(); final Uri uri = fetchState.getUri(); final Request request = new Request.Builder().cacheControl(new CacheControl.Builder().noStore().build()) .url(uri.toString()).get().build(); final Call call = mOkHttpClient.newCall(request); fetchState.getContext().addCallbacks(new BaseProducerContextCallbacks() { @Override/*from w w w.j a va2 s . co m*/ public void onCancellationRequested() { if (Looper.myLooper() != Looper.getMainLooper()) { call.cancel(); } else { mCancellationExecutor.execute(new Runnable() { @Override public void run() { call.cancel(); } }); } } }); call.enqueue(new com.squareup.okhttp.Callback() { @Override public void onResponse(Response response) { fetchState.responseTime = SystemClock.elapsedRealtime(); final ResponseBody body = response.body(); try { long contentLength = body.contentLength(); if (contentLength < 0) { contentLength = 0; } callback.onResponse(body.byteStream(), (int) contentLength); } catch (Exception e) { handleException(call, e, callback); } finally { try { body.close(); } catch (Exception e) { FLog.w(TAG, "Exception when closing response body", e); } } } @Override public void onFailure(final Request request, final IOException e) { handleException(call, e, callback); } }); }
From source file:com.facebook.imagepipeline.backends.okhttp.OkHttpNetworkFetchProducer.java
License:Open Source License
@Override protected void fetchImage(final NfpRequestState requestState) { final Uri uri = requestState.getUri(); final Request request = new Request.Builder().cacheControl(new CacheControl.Builder().noStore().build()) .url(uri.toString()).get().build(); final Call call = mOkHttpClient.newCall(request); if (mCancellable) { requestState.getContext().addCallbacks(new BaseProducerContextCallbacks() { @Override/*from ww w. ja v a 2 s.co m*/ public void onCancellationRequested() { call.cancel(); } }); } call.enqueue(new Callback() { @Override public void onResponse(Response response) { final ResponseBody body = response.body(); try { long contentLength = body.contentLength(); if (contentLength < 0) { contentLength = 0; } processResult(requestState, body.byteStream(), (int) contentLength, false); } catch (IOException ioe) { handleException(call, requestState, ioe); } finally { try { body.close(); } catch (IOException ioe) { FLog.w(TAG, "Exception when closing response body", ioe); } } } @Override public void onFailure(final Request request, final IOException e) { handleException(call, requestState, e); } }); }
From source file:com.kubeiwu.easyandroid.easyhttp.core.retrofit.KOkHttpCall.java
License:Apache License
private void exeRequest(final Callback<T> callback, final Request request, final boolean loadnetElseCache) { com.squareup.okhttp.Call rawCall; try {// ww w.ja v a 2s. c o m rawCall = client.newCall(request); } catch (Throwable t) { callback.onFailure(t); return; } if (canceled) { rawCall.cancel(); } this.rawCall = rawCall; callback.onstart(); 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) { if (canceled) { return; } callFailure(e); } @Override public void onResponse(com.squareup.okhttp.Response rawResponse) { if (canceled) { return; } Response<T> response; try { response = parseResponse(rawResponse, request); } catch (Throwable e) { if (loadnetElseCache) { cacheExecutor.execute(new CallbackRunnable<T>(callback, cacheCallbackExecutor) { @Override public Response<T> obtainResponse() { return execCacheRequest(request); } }); return; } callFailure(e); return; } callSuccess(response); } }); }
From source file:com.kubeiwu.easyandroid.easyhttp.core.retrofit.KOkHttpCall.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 va 2 s . c o m } final Request request = createRequest(); com.squareup.okhttp.Call rawCall = client.newCall(request); if (canceled) { rawCall.cancel(); } this.rawCall = rawCall; // ----------------------------------------------------------------------cgp String cacheMode = getCacheMode(request); if (!TextUtils.isEmpty(cacheMode)) { cacheMode = cacheMode.trim().toLowerCase(Locale.CHINA); switch (cacheMode) { case CacheMode.LOAD_NETWORK_ELSE_CACHE:// ?? Response<T> response; try { response = parseResponse(rawCall.execute(), request); } catch (Exception e) { response = execCacheRequest(request); } return response; case CacheMode.LOAD_CACHE_ELSE_NETWORK:// ? // ---------------------? response = execCacheRequest(request); if (response != null) { return response; } // ---------------------? // case CacheMode.LOAD_DEFAULT: case CacheMode.LOAD_NETWORK_ONLY: default: break;// } } // ----------------------------------------------------------------------cgp return parseResponse(rawCall.execute(), request); }