List of usage examples for com.squareup.okhttp Callback Callback
Callback
From source file:com.auth0.android.lock.internal.configuration.ApplicationFetcher.java
License:Open Source License
private void makeApplicationRequest(final AuthenticationCallback<List<Connection>> callback) { Uri uri = Uri.parse(account.getConfigurationUrl()).buildUpon().appendPath("client") .appendPath(account.getClientId() + ".js").build(); Request req = new Request.Builder().url(uri.toString()).build(); client.newCall(req).enqueue(new Callback() { @Override/*from www .j ava2 s .c om*/ public void onFailure(Request request, final IOException e) { Log.e(TAG, "Failed to fetch the Application: " + e.getMessage(), e); Auth0Exception exception = new Auth0Exception("Failed to fetch the Application: " + e.getMessage()); callback.onFailure(new AuthenticationException("Failed to fetch the Application", exception)); } @Override public void onResponse(Response response) { List<Connection> connections; try { connections = parseJSONP(response); } catch (Auth0Exception e) { Log.e(TAG, "Could not parse Application JSONP: " + e.getMessage()); callback.onFailure(new AuthenticationException("Could not parse Application JSONP", e)); return; } Log.i(TAG, "Application received!"); callback.onSuccess(connections); } }); }
From source file:com.ayuget.redface.ui.misc.ImageMenuHandler.java
License:Apache License
/** * Saves image from network using OkHttp. Picasso is not used because it would strip away the * EXIF data once the image is saved (Picasso directly gives us a Bitmap). *//*from w ww . ja v a2 s .c om*/ private void saveImageFromNetwork(final File mediaFile, final Bitmap.CompressFormat targetFormat, final boolean compressAsPng, final boolean notifyUser, final boolean broadcastSave, final ImageSavedCallback imageSavedCallback) { OkHttpClient okHttpClient = new OkHttpClient(); final Request request = new Request.Builder().url(imageUrl).build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { SnackbarHelper.makeError(activity, R.string.error_saving_image).show(); } @Override public void onResponse(Response response) throws IOException { final byte[] imageBytes = response.body().bytes(); Timber.d("Image successfully decoded, requesting WRITE_EXTERNAL_STORAGE permission to save image"); RxPermissions.getInstance(activity).request(Manifest.permission.WRITE_EXTERNAL_STORAGE) .subscribe(new Action1<Boolean>() { @Override public void call(Boolean granted) { if (granted) { Timber.d("WRITE_EXTERNAL_STORAGE granted, saving image to disk"); try { Timber.d("Saving image to %s", mediaFile.getAbsolutePath()); if (compressAsPng) { Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); StorageHelper.storeImageToFile(bitmap, mediaFile, targetFormat); } else { StorageHelper.storeImageToFile(imageBytes, mediaFile); } if (broadcastSave) { // First, notify the system that a new image has been saved // to external storage. This is important for user experience // because it makes the image visible in the system gallery // app. StorageHelper.broadcastImageWasSaved(activity, mediaFile, targetFormat); } if (notifyUser) { // Then, notify the user with an enhanced snackbar, allowing // him (or her) to open the image in his favorite app. Snackbar snackbar = SnackbarHelper.makeWithAction(activity, R.string.image_saved_successfully, R.string.action_snackbar_open_image, new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType( Uri.parse("file://" + mediaFile.getAbsolutePath()), "image/*"); activity.startActivity(intent); } }); snackbar.show(); } notifyImageWasSaved(imageSavedCallback, mediaFile, targetFormat); } catch (IOException e) { Timber.e(e, "Unable to save image to external storage"); SnackbarHelper.makeError(activity, R.string.error_saving_image).show(); } } else { Timber.w("WRITE_EXTERNAL_STORAGE denied, unable to save image"); SnackbarHelper .makeError(activity, R.string.error_saving_image_permission_denied) .show(); } } }); } }); }
From source file:com.bartoszlipinski.streetviewprobe.StreetViewProbe.java
License:Apache License
public synchronized void probe(final double lat, final double lon, final OnStreetViewStatusListener listener) { if (listener == null) { throw new IllegalArgumentException("Listener must not be null."); }/*from w ww. j a va2 s . c om*/ new Thread(new Runnable() { @Override public void run() { if (context.get() != null) { String path = context.get().getString(R.string.probe_path, size, lat, lon); client.newCall(new Request.Builder().url(path).build()).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { listener.onStreetViewStatus(Status.UNKNOWN); } @Override public void onResponse(Response response) throws IOException { // Log.d("BITM", response.body().contentLength() + " "); listener.onStreetViewStatus( response.body().contentLength() > threshold ? Status.AVAILABLE : Status.UNAVAILABLE); } }); } } }).start(); }
From source file:com.digi.wva.internal.HttpClient.java
License:Mozilla Public License
/** * Wrap an HttpCallback in an OkHttp {@link Callback} instance. * Also will automatically attempt to parse the response as JSON. * * <p>This method is protected, rather than private, due to a bug between JaCoCo and * the Android build tools which causes the instrumented bytecode to be invalid when this * method is private://from ww w . j a va 2 s. com * <a href="http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode" target="_blank">see StackOverflow question.</a> * </p> * @param callback the {@link com.digi.wva.internal.HttpClient.HttpCallback} to wrap * @return a corresponding {@link Callback} */ protected Callback wrapCallback(final HttpCallback callback) { return new Callback() { @Override public void onResponse(Response response) throws IOException { logResponse(response); Request request = response.request(); String responseBody = response.body().string(); if (response.isSuccessful()) { // Request succeeded. Parse JSON response. try { JSONObject parsed = new JSONObject(responseBody); callback.onSuccess(parsed); } catch (JSONException e) { callback.onJsonParseError(e, responseBody); } } else { int status = response.code(); String url = response.request().urlString(); Exception error; // Generate an appropriate exception based on the status code switch (status) { case 400: error = new WvaHttpBadRequest(url, responseBody); break; case 403: error = new WvaHttpForbidden(url, responseBody); break; case 404: error = new WvaHttpNotFound(url, responseBody); break; case 414: error = new WvaHttpRequestUriTooLong(url, responseBody); break; case 500: error = new WvaHttpInternalServerError(url, responseBody); break; case 503: error = new WvaHttpServiceUnavailable(url, responseBody); break; default: error = new WvaHttpException("HTTP " + status, url, responseBody); break; } callback.onFailure(error); } } @Override public void onFailure(Request request, IOException exception) { callback.onFailure(exception); } }; }
From source file:com.example.jony.myapp.reader_APP.ui.DailyDetailsActivity.java
License:Open Source License
@Override protected void onDataRefresh() { Request.Builder builder = new Request.Builder(); builder.url(url);/*from w ww . j a v a 2s. c om*/ Request request = builder.build(); HttpUtil.enqueue(request, new Callback() { @Override public void onFailure(Request request, IOException e) { handler.sendEmptyMessage(CONSTANT.ID_FAILURE); } @Override public void onResponse(Response response) throws IOException { String res = response.body().string(); DebugUtils.DLog(res); Gson gson = new Gson(); dailyDetailsBean = gson.fromJson(res, DailyDetailsBean.class); cache.execSQL(DailyTable.updateBodyContent(DailyTable.NAME, dailyDetailsBean.getTitle(), dailyDetailsBean.getBody())); cache.execSQL(DailyTable.updateBodyContent(DailyTable.COLLECTION_NAME, dailyDetailsBean.getTitle(), dailyDetailsBean.getBody())); cache.execSQL(DailyTable.updateLargePic(DailyTable.NAME, dailyDetailsBean.getTitle(), dailyDetailsBean.getImage())); cache.execSQL(DailyTable.updateLargePic(DailyTable.COLLECTION_NAME, dailyDetailsBean.getTitle(), dailyDetailsBean.getImage())); imageUrl = dailyDetailsBean.getImage(); body = dailyDetailsBean.getBody(); handler.sendEmptyMessage(CONSTANT.ID_SUCCESS); } }); }
From source file:com.example.test.myapplication.TestActivity.java
License:Apache License
private void initDatas() { new Thread(new Runnable() { @Override//from w w w . ja va 2s . c o m 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.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 w w w . j ava 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.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 www .j a v a2 s . 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.facebook.react.devsupport.DevServerHelper.java
License:Open Source License
public void isPackagerRunning(final PackagerStatusCallback callback) { String statusURL = createPacakgerStatusURL(getDebugServerHost()); Request request = new Request.Builder().url(statusURL).build(); mClient.newCall(request).enqueue(new Callback() { @Override//from w ww . j a va 2 s . c o m public void onFailure(Request request, IOException e) { Log.e(ReactConstants.TAG, "IOException requesting status from packager", e); callback.onPackagerStatusFetched(false); } @Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) { Log.e(ReactConstants.TAG, "Got non-success http code from packager when requesting status: " + response.code()); callback.onPackagerStatusFetched(false); return; } ResponseBody body = response.body(); if (body == null) { Log.e(ReactConstants.TAG, "Got null body response from packager when requesting status"); callback.onPackagerStatusFetched(false); return; } if (!PACKAGER_OK_STATUS.equals(body.string())) { Log.e(ReactConstants.TAG, "Got unexpected response from packager when requesting status: " + body.string()); callback.onPackagerStatusFetched(false); return; } callback.onPackagerStatusFetched(true); } }); }
From source file:com.facebook.react.devsupport.DevServerHelper.java
License:Open Source License
private void enqueueOnChangeEndpointLongPolling() { Request request = new Request.Builder().url(createOnChangeEndpointUrl()).tag(this).build(); Assertions.assertNotNull(mOnChangePollingClient).newCall(request).enqueue(new Callback() { @Override/* www . j ava2s .co m*/ public void onFailure(Request request, IOException e) { if (mOnChangePollingEnabled) { // this runnable is used by onchange endpoint poller to delay subsequent requests in case // of a failure, so that we don't flood network queue with frequent requests in case when // dev server is down FLog.d(ReactConstants.TAG, "Error while requesting /onchange endpoint", e); mRestartOnChangePollingHandler.postDelayed(new Runnable() { @Override public void run() { handleOnChangePollingResponse(false); } }, LONG_POLL_FAILURE_DELAY_MS); } } @Override public void onResponse(Response response) throws IOException { handleOnChangePollingResponse(response.code() == 205); } }); }