List of usage examples for com.squareup.okhttp Callback Callback
Callback
From source file:cn.ucai.superwechart.activity.LoginActivity.java
License:Open Source License
private void downloadUserAvatar() { OkHttpUtils2<Message> utils = new OkHttpUtils2(); utils.url(UserUtils.getContactAvatarPath(currentUsername)).targetClass(Message.class) .doInBackground(new Callback() { @Override//from w w w . j a va 2 s . c o m public void onFailure(Request request, IOException e) { Log.e(TAG, "IOException=" + e); } @Override public void onResponse(Response response) throws IOException { byte[] data = response.body().bytes(); String avatarUrl = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getUserProfileManager() .uploadUserAvatar(data); Log.e(TAG, "avatarUrl=" + avatarUrl); } }).execute(new OkHttpUtils2.OnCompleteListener<Message>() { @Override public void onSuccess(Message result) { Log.e(TAG, "result=" + result); } @Override public void onError(String result) { Log.e(TAG, "result=" + result); } }); }
From source file:cn.ucai.SuperWechat.activity.LoginActivity.java
License:Open Source License
private void UpdateUserAvatar() { final OkHttpUtils2<Message> utils = new OkHttpUtils2<Message>(); utils.setRequestUrl(I.REQUEST_DOWNLOAD_AVATAR).addParam(I.NAME_OR_HXID, currentUsername) .addParam(I.AVATAR_TYPE, I.AVATAR_TYPE_USER_PATH).targetClass(Message.class) .doInBackground(new Callback() { @Override// w w w .jav a 2 s. c o m public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { byte[] bytes = response.body().bytes(); final String avatarUrl = ((DemoHXSDKHelper) HXSDKHelper.getInstance()) .getUserProfileManager().uploadUserAvatar(bytes); } }); }
From source file:cn.wochu.wh.net.OkHttpClientManager.java
License:Apache License
/** * /*from ww w .ja v a 2 s. co m*/ * * @param url * @param destFileDir * @param callback */ private void _downloadAsyn(final String url, final String destFileDir, final ResultCallback callback) { final Request request = new Request.Builder().url(url).build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(final Request request, final IOException e) { sendFailedStringCallback(request, e, callback); } @Override public void onResponse(Response response) { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; try { is = response.body().byteStream(); File file = new File(destFileDir, getFileName(url)); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); //??? sendSuccessResultCallback(file.getAbsolutePath(), callback); } catch (IOException e) { sendFailedStringCallback(response.request(), e, callback); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } } }); }
From source file:cn.wochu.wh.net.OkHttpClientManager.java
License:Apache License
private void deliveryResult(final ResultCallback callback, Request request) { callback.onBefore(request);//from w w w . ja va 2 s . co m mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(final Request request, final IOException e) { //sendFailedStringCallback(request, e, callback); callback.onError(request, e); callback.onAfter(); } @Override public void onResponse(final Response response) { try { final String string = response.body().string(); if (callback.mType == String.class) { sendSuccessResultCallback(string, callback); } else { Object o = mGson.fromJson(string, callback.mType); sendSuccessResultCallback(o, callback); } } catch (IOException e) { sendFailedStringCallback(response.request(), e, callback); } catch (com.google.gson.JsonParseException e)//Json? { sendFailedStringCallback(response.request(), e, callback); } } }); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void exceptionThrownByOnResponseIsRedactedAndLogged() throws Exception { server.enqueue(new MockResponse()); Request request = new Request.Builder().url(server.getUrl("/secret")).build(); client.newCall(request).enqueue(new Callback() { @Override//from www.j a v a2 s . c om public void onFailure(Request request, IOException e) { fail(); } @Override public void onResponse(Response response) throws IOException { throw new IOException("a"); } }); assertEquals("INFO: Callback failure for call to " + server.getUrl("/") + "...", logHandler.take()); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void connectionReuseWhenResponseBodyConsumed_Async() throws Exception { server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("def")); Request request = new Request.Builder().url(server.getUrl("/a")).build(); client.newCall(request).enqueue(new Callback() { @Override/*from ww w. j a v a2 s . c o m*/ public void onFailure(Request request, IOException e) { throw new AssertionError(); } @Override public void onResponse(Response response) throws IOException { InputStream bytes = response.body().byteStream(); assertEquals('a', bytes.read()); assertEquals('b', bytes.read()); assertEquals('c', bytes.read()); // This request will share a connection with 'A' cause it's all done. client.newCall(new Request.Builder().url(server.getUrl("/b")).build()).enqueue(callback); } }); callback.await(server.getUrl("/b")).assertCode(200).assertBody("def"); assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection reuse! }
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 a v a2 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 asyncResponseCanBeConsumedLater() throws Exception { server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("def")); Request request = new Request.Builder().url(server.getUrl("/")).header("User-Agent", "SyncApiTest").build(); final BlockingQueue<Response> responseRef = new SynchronousQueue<>(); client.newCall(request).enqueue(new Callback() { @Override//from w w w .j av a2s.c o m public void onFailure(Request request, IOException e) { throw new AssertionError(); } @Override public void onResponse(Response response) throws IOException { try { responseRef.put(response); } catch (InterruptedException e) { throw new AssertionError(); } } }); Response response = responseRef.take(); assertEquals(200, response.code()); assertEquals("abc", response.body().string()); // Make another request just to confirm that that connection can be reused... FiberOkHttpTestUtil.executeInFiberRecorded(client, new Request.Builder().url(server.getUrl("/")).build()) .assertBody("def"); assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection reused. // ... even before we close the response body! response.body().close(); }
From source file:com.alibaba.weex.update.Downloader.java
License:Apache License
public static void download(String url, final DownloadCallback callback) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).get().build(); client.newCall(request).enqueue(new Callback() { @Override//w w w .j av a 2 s . c o m public void onFailure(Request request, IOException e) { callback.onError(e); } @Override public void onResponse(Response response) throws IOException { callback.handleResponse(response); } }); }
From source file:com.anony.okhttp.sample.AsynchronousGet.java
License:Apache License
public void run() throws Exception { Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build(); client.newCall(request).enqueue(new Callback() { @Override// www. j a va 2s. co m public void onFailure(Request request, IOException e) { e.printStackTrace(); } @Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0, size = responseHeaders.size(); i < size; i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } System.out.println(response.body().string()); } }); }