List of usage examples for com.squareup.okhttp Response isSuccessful
public boolean isSuccessful()
From source file:com.commonsware.android.okhttp.LoadThread.java
License:Apache License
@Override public void run() { try {// w w w. j a v a 2s. c o m 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.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 ww . jav a2s.co 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; }
From source file:com.dgmltn.upnpbrowser.UPnPDevice.java
License:Apache License
public void downloadSpecs() throws Exception { Request request = new Request.Builder().url(mLocation).build(); Response response = mClient.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); }/*from w w w .j av a2 s . com*/ mRawXml = response.body().string(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource source = new InputSource(new StringReader(mRawXml)); Document doc; try { doc = db.parse(source); } catch (SAXParseException e) { return; } XPath xPath = XPathFactory.newInstance().newXPath(); mProperties.put("xml_icon_url", xPath.compile("//icon/url").evaluate(doc)); generateIconUrl(); mProperties.put("xml_friendly_name", xPath.compile("//friendlyName").evaluate(doc)); }
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 w w w . j ava 2 s. c o m * <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.dreamfactory.kurtishu.pretty.view.task.DownloadImagTask.java
License:Apache License
private void downloadImg(String url) { Request request = new Request.Builder().url(url).build(); OkHttpClient okHttpClient = new OkHttpClient(); try {/*w ww. j av a2 s . c o m*/ Response response = okHttpClient.newCall(request).execute(); if (null != response && response.isSuccessful()) { String filePath = storeImgToSDCard(response.body().byteStream()); setPostMessage(EXECUTE_STATE_DOWNLOAD_SUCCESS, filePath); } else { setPostMessage(ExecutableThread.EXECUTE_STATE_FAILURE, "Internet error!"); } } catch (IOException e) { Logger.e("Error message: " + e.toString()); setPostMessage(ExecutableThread.EXECUTE_STATE_FAILURE, e.getMessage()); } }
From source file:com.example.sample2.ExampleFragment1.java
License:Apache License
@Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { final String body = response.body().string(); mSchedule = gson.fromJson(body, BBCSchedule.class); scheduleList.post(new Runnable() { @Override//from w w w. j ava2 s. c o m public void run() { scheduleList.setAdapter(new ScheduleAdapter(mSchedule.getSchedule().getDay().getBroadcasts())); } }); } }
From source file:com.examples.abelanav2.grpcclient.CloudStorage.java
License:Open Source License
/** * Uploads an image to Google Cloud Storage. * @param url the upload url.//from w ww .j a v a2 s. c o m * @param bitmap the image to upload. * @throws IOException if cannot upload the image. */ public static void uploadImage(String url, Bitmap bitmap) throws IOException { ByteArrayOutputStream bOS = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOS); byte[] bitmapData = bOS.toByteArray(); InputStream stream = new ByteArrayInputStream(bitmapData); String contentType = URLConnection.guessContentTypeFromStream(stream); InputStreamContent content = new InputStreamContent(contentType, stream); MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg"); OkHttpClient client = new OkHttpClient(); RequestBody requestBody = RequestBodyUtil.create(MEDIA_TYPE_JPEG, content.getInputStream()); Request request = new Request.Builder().url(url).put(requestBody).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } }
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 ww w . java 2 s . c om 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// ww w.j a v a 2s . c om 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.github.drrb.surefiresplitter.go.GoServer.java
License:Open Source License
private ResponseBody get(String url) throws CommunicationError { Request.Builder requestBuilder = new Request.Builder().get().url(url); if (username != null && password != null) { requestBuilder.addHeader("Authorization", Credentials.basic(username, password)); }/*from ww w. j ava 2s . c o m*/ Response response = execute(requestBuilder.build()); if (response.isSuccessful()) { return response.body(); } else { String errorMessage = String.format("Bad status code when requesting: %s (%d: %s)", url, response.code(), response.message()); try (ResponseBody responseBody = response.body()) { errorMessage += ("\n" + responseBody.string()); } catch (IOException e) { errorMessage += ". Tried to read the response body for a helpful message, but couldn't (Error was '" + e.getMessage() + "')."; } throw new CommunicationError(errorMessage); } }