List of usage examples for com.squareup.okhttp Call enqueue
public void enqueue(Callback responseCallback)
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void illegalToExecuteTwice_Async() throws Exception { server.enqueue(new MockResponse().setBody("abc").addHeader("Content-Type: text/plain")); Request request = new Request.Builder().url(server.getUrl("/")).header("User-Agent", "SyncApiTest").build(); Call call = client.newCall(request); call.enqueue(callback); try {/* w ww . j a v a 2 s . c o m*/ FiberOkHttpUtil.executeInFiber(call); fail(); } catch (IllegalStateException e) { assertEquals("Already Executed", e.getMessage()); } try { FiberOkHttpUtil.executeInFiber(call); fail(); } catch (IllegalStateException e) { assertEquals("Already Executed", e.getMessage()); } assertEquals("SyncApiTest", server.takeRequest().getHeader("User-Agent")); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void cancelTagImmediatelyAfterEnqueue() throws Exception { Call call = client.newCall(new Request.Builder().url(server.getUrl("/a")).tag("request").build()); call.enqueue(callback); client.cancel("request"); assertEquals(0, server.getRequestCount()); callback.await(server.getUrl("/a")).assertFailure("Canceled"); }
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 .ja va 2s. 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 www . ja v a 2s . 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:com.example.test.myapplication.TestActivity.java
License:Apache License
private void initDatas() { new Thread(new Runnable() { @Override/* w ww .j a v a 2s . c om*/ public void run() { OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder().url("https://www.baidu.com/index.php").build(); Call response = okHttpClient.newCall(request); response.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.i("Response", e.toString()); } @Override public void onResponse(Response response) throws IOException { Log.i("Response", response.body().toString()); mDatas.add(response.toString()); runOnUiThread(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); } }); } }).start(); }
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 www. ja v a2 s . com*/ 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/* w w w . j av a2 s. c om*/ 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.facebook.react.devsupport.DevServerHelper.java
License:Open Source License
public void downloadBundleFromURL(final BundleDownloadCallback callback, final String jsModulePath, final File outputFile) { final String bundleURL = createBundleURL(getDebugServerHost(), jsModulePath, getDevMode()); Request request = new Request.Builder().url(bundleURL).build(); Call call = mClient.newCall(request); call.enqueue(new Callback() { @Override//from w w w . ja v a 2s .c o m public void onFailure(Request request, IOException e) { callback.onFailure(e); } @Override public void onResponse(Response response) throws IOException { // Check for server errors. If the server error has the expected form, fail with more info. if (!response.isSuccessful()) { String body = response.body().string(); DebugServerException debugServerException = DebugServerException.parse(body); if (debugServerException != null) { callback.onFailure(debugServerException); } else { callback.onFailure(new IOException("Unexpected response code: " + response.code())); } return; } Sink output = null; try { output = Okio.sink(outputFile); Okio.buffer(response.body().source()).readAll(output); callback.onSuccess(); } finally { if (output != null) { output.close(); } } } }); }
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 {//from w w w . j av a2s . c om 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.liferay.mobile.android.auth.CookieSignIn.java
License:Open Source License
public static void signIn(Session session, CookieCallback callback, Authenticator authenticator) { try {/*from w w w .j a v a 2 s . c om*/ CookieSignIn cookieSignIn = new CookieSignIn(session); Call call = cookieSignIn.signIn(); Callback requestCallback = getCallback(session.getServer(), callback, cookieSignIn.cookieManager, getCookieAuthentication(session.getAuthentication())); call.enqueue(requestCallback); } catch (Exception e) { callback.onFailure(e); } }