List of usage examples for com.squareup.okhttp OkHttpClient newCall
public Call newCall(Request request)
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). *//*w w w . j a v a 2s .c o m*/ 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.brq.wallet.bitid.BitIdAuthenticator.java
License:Microsoft Reference Source License
public BitIdResponse queryServer() { final BitIdResponse bitIdResponse = new BitIdResponse(); final SignedMessage signature = privateKey.signMessage(request.getFullUri()); try {//from w w w . ja v a2 s . co m OkHttpClient client = getOkHttpClient(); Request request = getRequest(signature); Response callResponse = client.newCall(request).execute(); bitIdResponse.code = callResponse.code(); if (bitIdResponse.code >= 200 && bitIdResponse.code < 300) { bitIdResponse.status = BitIdResponse.ResponseStatus.SUCCESS; bitIdResponse.message = callResponse.body().string(); } else { bitIdResponse.status = BitIdResponse.ResponseStatus.ERROR; bitIdResponse.message = formatErrorMessage(callResponse.body().string()); } } catch (SocketTimeoutException e) { //connection timed out bitIdResponse.status = BitIdResponse.ResponseStatus.TIMEOUT; } catch (InterruptedIOException e) { //seems like this can also happen when a timeout occurs bitIdResponse.status = BitIdResponse.ResponseStatus.TIMEOUT; } catch (UnknownHostException e) { //host not known, most probably the device has no internet connection bitIdResponse.status = BitIdResponse.ResponseStatus.NOCONNECTION; } catch (ConnectException e) { //might be a refused connection bitIdResponse.status = BitIdResponse.ResponseStatus.REFUSED; } catch (SSLException e) { Preconditions.checkState(enforceSslCorrectness); //ask user whether he wants to proceed although there is a problem with the certificate bitIdResponse.message = e.getLocalizedMessage(); bitIdResponse.status = BitIdResponse.ResponseStatus.SSLPROBLEM; } catch (IOException e) { throw new RuntimeException(e); } return bitIdResponse; }
From source file:com.capstone.transit.trans_it.TripPlannerActivity.java
License:Open Source License
private void getDirections(LatLng origin, LatLng destination) { final String directionsURL = getDirectionsUrl(origin, destination); Log.v(TAG, directionsURL);//from w w w. ja v a2s . co m if (isNetworkAvailable()) { Thread T = new Thread() { public void run() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(directionsURL).build(); Call call = client.newCall(request); try { Response response = call.execute(); String jsonData = response.body().string(); Log.v(TAG, jsonData); if (response.isSuccessful()) { mStep = getSteps(jsonData); } else { alertUserAboutError(); } } catch (JSONException | IOException e) { e.printStackTrace(); } } }; T.start(); try { T.join(); } catch (InterruptedException e) { e.printStackTrace(); } } else { Toast.makeText(this, "unavailable network", Toast.LENGTH_LONG).show(); } }
From source file:com.cdancy.artifactory.rest.config.ArtifactoryOkHttpCommandExecutorService.java
License:Apache License
@Override protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException { OkHttpClient requestScopedClient = clientSupplier.get(); requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri())); Response response = requestScopedClient.newCall(nativeRequest).execute(); HttpResponse.Builder<?> builder = HttpResponse.builder(); builder.statusCode(response.code()); builder.message(response.message()); Builder<String, String> headerBuilder = ImmutableMultimap.builder(); Headers responseHeaders = response.headers(); // Check for Artifactory header and init potential file for downstream use File destinationFile = null;//from w w w.j a va2 s .co m String artFileName = responseHeaders.get("X-Artifactory-Filename"); if (artFileName != null) { GAVCoordinates gavCoordinates = ArtifactoryUtils.gavFromURL(nativeRequest.url(), endpoint.get().toURL()); destinationFile = ArtifactoryUtils.getGradleFile(gavCoordinates, artFileName, responseHeaders.get("ETag")); headerBuilder.put(ArtifactoryUtils.LOCATION_HEADER, destinationFile.getAbsolutePath()); } for (String header : responseHeaders.names()) { headerBuilder.putAll(header, responseHeaders.values(header)); } ImmutableMultimap<String, String> headers = headerBuilder.build(); if (response.code() == 204 && response.body() != null) { response.body().close(); } else { if (destinationFile != null) { if (!destinationFile.exists() || (destinationFile.length() != response.body().contentLength())) { InputStream inputStream = null; try { inputStream = response.body().byteStream(); ArtifactoryUtils.resolveInputStream(inputStream, destinationFile); } catch (Exception e) { Throwables.propagate(e); } finally { if (inputStream != null) { inputStream.close(); } } } IOUtils.closeQuietly(response.body().byteStream()); } else { Payload payload = newInputStreamPayload(response.body().byteStream()); contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); builder.payload(payload); } } builder.headers(filterOutContentHeaders(headers)); return builder.build(); }
From source file:com.codemodlabs.coordinate.Token.java
License:Open Source License
private void executeCallback(String url) { class CallbackTask extends AsyncTask { @Override/* www.j a v a2 s. c o m*/ protected Object doInBackground(Object[] objects) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url((String) objects[0]).build(); Response response = null; String body_string = ""; try { response = client.newCall(request).execute(); body_string = response.body().string(); } catch (IOException e) { e.printStackTrace(); } Gson gson = new Gson(); callback = gson.fromJson(body_string, Callback.class); return callback; } @Override protected void onPostExecute(Object result) { super.onPostExecute(result); try { getTokenFromServer((Callback) result); } catch (IOException e) { e.printStackTrace(); } } } new CallbackTask().execute(url); }
From source file:com.codemodlabs.coordinate.Token.java
License:Open Source License
private void getTokenFromServer(Callback callback) throws IOException { class GetTokenTask extends AsyncTask { @Override/*w w w . j a v a 2s.c o m*/ protected Object doInBackground(Object[] objects) { try { final String access_code = ((Callback) objects[0]).access_code; String url_string = "https://login.uber.com/oauth/token"; OkHttpClient client = new OkHttpClient(); // Ignore invalid SSL endpoints. client.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); RequestBody formBody = new FormEncodingBuilder().add("client_secret", client_secret) .add("client_id", client_id).add("grant_type", "authorization_code") .add("redirect_uri", redirect_url).add("code", access_code).build(); Request request = new Request.Builder().url(url_string).post(formBody).build(); Response response = client.newCall(request).execute(); String response_body = response.body().string(); Gson gson = new Gson(); token = gson.fromJson(response_body, Token.class); return token; } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Object result) { super.onPostExecute(result); Token token = (Token) result; Intent resultIntent = new Intent(); resultIntent.putExtra("access_token", token.access_token); resultIntent.putExtra("expires_in", token.expires_in); resultIntent.putExtra("token_type", token.token_type); resultIntent.putExtra("refresh_token", token.refresh_token); resultIntent.putExtra("scope", token.scope); setResult(2, resultIntent); finish(); } } new GetTokenTask().execute(callback); }
From source file:com.coinomi.wallet.ExchangeRatesProvider.java
License:Open Source License
@Nullable private JSONObject requestExchangeRatesJson(final URL url) { // Return null if no connection final NetworkInfo activeInfo = connManager.getActiveNetworkInfo(); if (activeInfo == null || !activeInfo.isConnected()) return null; final long start = System.currentTimeMillis(); OkHttpClient client = NetworkUtils.getHttpClient(getContext().getApplicationContext()); Request request = new Request.Builder().url(url).build(); try {/*from w w w .jav a 2 s. co m*/ Response response = client.newCall(request).execute(); if (response.isSuccessful()) { log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, System.currentTimeMillis() - start); return new JSONObject(response.body().string()); } else { log.warn("Error HTTP code '{}' when fetching exchange rates from {}", response.code(), url); } } catch (IOException e) { log.warn("Error '{}' when fetching exchange rates from {}", e.getMessage(), url); } catch (JSONException e) { log.warn("Could not parse exchange rates JSON: {}", e.getMessage()); } return null; }
From source file:com.commonsware.android.okhttp.LoadThread.java
License:Apache License
@Override public void run() { try {/* ww w . j av a 2 s .com*/ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(SO_URL).build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { Reader in = response.body().charStream(); BufferedReader reader = new BufferedReader(in); SOQuestions questions = new Gson().fromJson(reader, SOQuestions.class); reader.close(); EventBus.getDefault().post(new QuestionsLoadedEvent(questions)); } else { Log.e(getClass().getSimpleName(), response.toString()); } } catch (Exception e) { Log.e(getClass().getSimpleName(), "Exception parsing JSON", e); } }
From source file:com.creapple.tms.mobiledriverconsole.utils.MDCUtils.java
License:Creative Commons License
/** * Get distance information between two GPS * @param originLat/* w w w .ja va 2s. c o m*/ * @param originLon * @param destLat * @param destLon * @return */ public static String[] getDistanceInfo(double originLat, double originLon, double destLat, double destLon) { String[] infos = new String[] { "0", "0" }; String address = Constants.GOOGLE_DISTANCE_MATRIX_ADDRESS; address += originLat + "," + originLon; address += "&destinations="; address += destLat + "," + destLon; address += "&mode=driving&units=metric&language=en&key="; address += Constants.GOOGLE_DISTANCE_MATRIX_API_KEY; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(address).build(); Response response = null; String dist = null; try { response = client.newCall(request).execute(); dist = response.body().string(); } catch (IOException e) { return infos; } Log.d("@@@@@@", dist); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = null; try { jsonObject = (JSONObject) jsonParser.parse(dist); } catch (ParseException e) { return infos; } // status check as well JSONArray rows = (JSONArray) jsonObject.get(Constants.GOOGLE_DISTANCE_MATRIX_ROWS); for (int i = 0; i < rows.size(); i++) { JSONObject obj = (JSONObject) rows.get(i); JSONArray elements = (JSONArray) obj.get(Constants.GOOGLE_DISTANCE_MATRIX_ELEMENTS); for (int j = 0; j < elements.size(); j++) { JSONObject datas = (JSONObject) elements.get(j); JSONObject distance = (JSONObject) datas.get(Constants.GOOGLE_DISTANCE_MATRIX_DISTANCE); JSONObject duration = (JSONObject) datas.get(Constants.GOOGLE_DISTANCE_MATRIX_DURATION); infos[0] = distance.get(Constants.GOOGLE_DISTANCE_MATRIX_VALUE) + ""; infos[1] = duration.get(Constants.GOOGLE_DISTANCE_MATRIX_TEXT) + ""; } } String status = jsonObject.get(Constants.GOOGLE_DISTANCE_MATRIX_STATUS).toString(); // Log.d("@@@@@@", status); if (!StringUtils.equalsIgnoreCase(Constants.GOOGLE_DISTANCE_MATRIX_OK, status)) { return infos; } return infos; }
From source file:com.crownpay.wallet.ExchangeRatesProvider.java
License:Open Source License
@Nullable private JSONObject requestExchangeRatesJson(final URL url) { // Return null if no connection final NetworkInfo activeInfo = connManager.getActiveNetworkInfo(); if (activeInfo == null || !activeInfo.isConnected()) return null; final long start = System.currentTimeMillis(); OkHttpClient client = NetworkUtils.getHttpClient(getContext().getApplicationContext()); Request request = new Request.Builder().url(url).build(); try {//from w w w. j a va 2s . c o m Response response = client.newCall(request).execute(); if (response.isSuccessful()) { log.info("fetched exchange rates from {}, took {} ms", url, System.currentTimeMillis() - start); return new JSONObject(response.body().string()); } else { log.warn("Error HTTP code '{}' when fetching exchange rates from {}", response.code(), url); } } catch (IOException e) { log.warn("Error '{}' when fetching exchange rates from {}", e.getMessage(), url); } catch (JSONException e) { log.warn("Could not parse exchange rates JSON: {}", e.getMessage()); } return null; }