List of usage examples for com.squareup.okhttp Response isSuccessful
public boolean isSuccessful()
From source file:com.github.leonardoxh.temporeal.app.service.NoticeService.java
License:Apache License
@Override protected void onHandleIntent(Intent intent) { Response response = makeRequest(Constants.NOTICE_ENDPOINT, null); if (response.isSuccessful()) { try {// www . j a v a2 s .c o m List<Notice> notices = JsonUtils.listFromJson(response.body().string(), Notice.class); if (!notices.isEmpty()) { NoticeDao noticeDao = new NoticeDao(this); noticeDao.saveAllNotices(notices); } } catch (IOException e) { /* Podemos simplesmente ignorar essa exception * por que teremos uma falha de leitura, entao na * proxima sincronizacao tudo sera sincronizado */ e.printStackTrace(); } } }
From source file:com.github.leonardoxh.temporeal.app.service.UserService.java
License:Apache License
@Override protected void onHandleIntent(Intent intent) { User user = intent.getExtras().getParcelable(EXTRA_USER); Response response = makeRequest(Constants.USER_ENDPOINT, user); if (response.isSuccessful()) { try {//from ww w . j a va2 s .c o m User serverUser = JsonUtils.fromJson(response.body().string(), User.class); /* O usuario foi cadastrado no servidor corretamente, entao so persistimos ele * e indicamos a nossa Activity o sucesso do mesmo */ new UserDao(this).saveOrUpdate(serverUser); sendSuccess(serverUser); } catch (IOException e) { /* Essa exception sera lancada caso tenhamos alguma falha na * leitura da resposta do servidor */ e.printStackTrace(); sendFailure(); } } else { sendFailure(); } }
From source file:com.github.pockethub.android.ui.comment.RawCommentFragment.java
License:Apache License
@Override public void onActivityResult(final int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_SELECT_PHOTO && resultCode == Activity.RESULT_OK) { showProgressIndeterminate(R.string.loading); ImageBinPoster.post(getActivity(), data.getData(), new Callback() { @Override/* ww w . jav a 2s. c o m*/ public void onFailure(Request request, IOException e) { dismissProgress(); showImageError(); } @Override public void onResponse(Response response) throws IOException { dismissProgress(); if (response.isSuccessful()) { insertImage(ImageBinPoster.getUrl(response.body().string())); } else { showImageError(); } } }); } }
From source file:com.github.pockethub.android.util.HttpImageGetter.java
License:Apache License
@Override public Drawable getDrawable(final String source) { try {//from w ww . j a v a2s . com Drawable repositoryImage = requestRepositoryImage(source); if (repositoryImage != null) return repositoryImage; } catch (Exception e) { // Ignore and attempt request over regular HTTP request } try { String logMessage = "Loading image: " + source; Log.d(getClass().getSimpleName(), logMessage); Bugsnag.leaveBreadcrumb(logMessage); Request request = new Request.Builder().get().url(source).build(); com.squareup.okhttp.Response response = okHttpClient.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected response code: " + response.code()); Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream()); if (bitmap == null) return loading.getDrawable(source); BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error loading image", e); Bugsnag.notify(e); return loading.getDrawable(source); } }
From source file:com.google.android.gcm.demo.app.DemoActivity.java
License:Apache License
private boolean registerToUniqush(String registrationId) throws IOException { RequestBody formBody = new FormEncodingBuilder().add("service", "ZenUI_PushService_5") .add("subscriber", "uniqush.client").add("pushservicetype", "gcm").add("regid", registrationId) .build();// w ww . ja v a 2s . com String url = "http://140.128.101.214:9898/subscribe"; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).post(formBody).build(); Response response = client.newCall(request).execute(); return response.isSuccessful(); }
From source file:com.google.android.gcm.demo.app.DemoActivity.java
License:Apache License
private boolean registerToPushd(String registrationId) throws IOException { String host = "http://vps.semoncat.com/push"; RequestBody formBody = new FormEncodingBuilder().add("proto", "gcm").add("token", registrationId) .add("lang", Locale.getDefault().toString()).add("timezone", TimeZone.getDefault().getID()).build(); String url = host + "/subscribers"; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() //.header("Authorization", getAuthHeader("SemonCat", "zoe80904")) .url(url).post(formBody).build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String id = new Gson().fromJson(response.body().string(), JsonObject.class).get("id").getAsString(); Log.d(TAG, "Id:" + id); //subscriber RequestBody subscriberFormBody = new FormEncodingBuilder().add("ignore_message", "0").build(); String subscriberUrl = host + "/subscriber/%s/subscriptions/zenui_help"; Request subscriberRequest = new Request.Builder() //.header("Authorization", getAuthHeader("SemonCat", "zoe80904")) .url(String.format(subscriberUrl, id)).post(subscriberFormBody).build(); Response subscriberResponse = client.newCall(subscriberRequest).execute(); return subscriberResponse.isSuccessful(); }// w ww .j a va 2 s . c o m return false; }
From source file:com.google.caliper.runner.resultprocessor.OkHttpUploadHandler.java
License:Apache License
@Override public boolean upload(URI uri, String content, String mediaType, Optional<UUID> apiKey, Trial trial) { HttpUrl url = HttpUrl.get(uri);/* ww w. j a v a 2 s .c o m*/ if (apiKey.isPresent()) { url = url.newBuilder().addQueryParameter("key", apiKey.get().toString()).build(); } RequestBody body = RequestBody.create(MediaType.parse(mediaType), content); Request request = new Request.Builder().url(url).post(body).build(); try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return true; } else { ResultsUploader.logger.fine("Failed upload response: " + response.code()); } } catch (IOException e) { ResultsUploader.logUploadFailure(trial, e); } return false; }
From source file:com.google.maps.internal.OkHttpPendingResult.java
License:Open Source License
private T parseResponse(OkHttpPendingResult<T, R> request, Response response) throws Exception { if (RETRY_ERROR_CODES.contains(response.code()) && cumulativeSleepTime < errorTimeOut) { // Retry is a blocking method, but that's OK. If we're here, we're either in an await() // call, which is blocking anyway, or we're handling a callback in a separate thread. return request.retry(); } else if (!response.isSuccessful()) { // The APIs return 200 even when the API request fails, as long as the transport mechanism // succeeds. INVALID_RESPONSE, etc are handled by the Gson parsing below. throw new IOException(String.format("Server Error: %d %s", response.code(), response.message())); }// w ww.j a v a2 s . c o m Gson gson = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeAdapter()) .registerTypeAdapter(Distance.class, new DistanceAdapter()) .registerTypeAdapter(Duration.class, new DurationAdapter()) .registerTypeAdapter(AddressComponentType.class, new SafeEnumAdapter<AddressComponentType>(AddressComponentType.UNKNOWN)) .registerTypeAdapter(AddressType.class, new SafeEnumAdapter<AddressType>(AddressType.UNKNOWN)) .registerTypeAdapter(TravelMode.class, new SafeEnumAdapter<TravelMode>(TravelMode.UNKNOWN)) .registerTypeAdapter(LocationType.class, new SafeEnumAdapter<LocationType>(LocationType.UNKNOWN)) .setFieldNamingPolicy(fieldNamingPolicy).create(); byte[] bytes = getBytes(response); R resp = gson.fromJson(new String(bytes, "utf8"), responseClass); if (resp.successful()) { // Return successful responses return resp.getResult(); } else { ApiException e = resp.getError(); if (e instanceof OverQueryLimitException && cumulativeSleepTime < errorTimeOut) { // Retry over_query_limit errors return request.retry(); } else { // Throw anything else, including OQLs if we've spent too much time retrying throw e; } } }
From source file:com.google.sample.beaconservice.ManageBeaconFragment.java
License:Open Source License
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_manage_beacon, container, false); advertisedId_Type = (TextView) rootView.findViewById(R.id.advertisedId_Type); advertisedId_Id = (TextView) rootView.findViewById(R.id.advertisedId_Id); status = (TextView) rootView.findViewById(R.id.status); placeId = (TextView) rootView.findViewById(R.id.placeId); placeId.setOnClickListener(new View.OnClickListener() { @Override/*ww w . j a v a 2 s. co m*/ public void onClick(View v) { editLatLngAction(); } }); latLng = (TextView) rootView.findViewById(R.id.latLng); latLng.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editLatLngAction(); } }); mapView = (ImageView) rootView.findViewById(R.id.mapView); mapView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editLatLngAction(); } }); expectedStability = (TextView) rootView.findViewById(R.id.expectedStability); expectedStability.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle("Edit Stability"); final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.stability_enums, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); final Spinner spinner = new Spinner(getActivity()); spinner.setAdapter(adapter); // Set the position of the spinner to the current value. if (beacon.expectedStability != null && !beacon.expectedStability.equals(Beacon.STABILITY_UNSPECIFIED)) { for (int i = 0; i < spinner.getCount(); i++) { if (beacon.expectedStability.equals(spinner.getItemAtPosition(i))) { spinner.setSelection(i); } } } builder.setView(spinner); builder.setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { beacon.expectedStability = (String) spinner.getSelectedItem(); updateBeacon(); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } }); description = (TextView) rootView.findViewById(R.id.description); description.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle("Edit description"); final EditText editText = new EditText(getActivity()); editText.setText(description.getText()); builder.setView(editText); builder.setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { beacon.description = editText.getText().toString(); updateBeacon(); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } }); actionButton = (Button) rootView.findViewById(R.id.actionButton); decommissionButton = (Button) rootView.findViewById(R.id.decommissionButton); decommissionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(getActivity()).setTitle("Decommission Beacon") .setMessage("Are you sure you want to decommission this beacon? This operation is " + "irreversible and the beacon cannot be registered again") .setPositiveButton("Decommission", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Callback decommissionCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { beacon.status = Beacon.STATUS_DECOMMISSIONED; updateBeacon(); } else { String body = response.body().string(); logErrorAndToast("Unsuccessful decommissionBeacon request: " + body); } } }; client.decommissionBeacon(decommissionCallback, beacon.getBeaconName()); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } }); attachmentsDivider = rootView.findViewById(R.id.attachmentsDivider); attachmentsLabel = (TextView) rootView.findViewById(R.id.attachmentsLabel); attachmentsTable = (TableLayout) rootView.findViewById(R.id.attachmentsTableLayout); // Fetch the namespace for the developer console project ID. We redraw the UI once that // request completes. // TODO: cache this. Callback listNamespacesCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(Response response) throws IOException { String body = response.body().string(); if (response.isSuccessful()) { try { JSONObject json = new JSONObject(body); JSONArray namespaces = json.getJSONArray("namespaces"); // At present there can be only one namespace. String tmp = namespaces.getJSONObject(0).getString("namespaceName"); if (tmp.startsWith("namespaces/")) { namespace = tmp.substring("namespaces/".length()); } else { namespace = tmp; } Log.d(Constants.TEST_TAG, "Namespace " + namespace); redraw(); } catch (JSONException e) { Log.e(TAG, "JSONException", e); } } else { logErrorAndToast("Unsuccessful listNamespaces request: " + body); } } }; client.listNamespaces(listNamespacesCallback); return rootView; }
From source file:com.google.sample.beaconservice.ManageBeaconFragment.java
License:Open Source License
private void updateBeacon() { // If the beacon hasn't been registered or was decommissioned, redraw the view and let the // commit happen in the parent action. if (beacon.status.equals(Beacon.UNREGISTERED) || beacon.status.equals(Beacon.STATUS_DECOMMISSIONED)) { redraw();/* ww w .j a v a2 s . c om*/ return; } Callback updateBeaconCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(Response response) throws IOException { String body = response.body().string(); if (response.isSuccessful()) { try { beacon = new Beacon(new JSONObject(body)); } catch (JSONException e) { logErrorAndToast("Failed JSON creation from response: " + body, e); return; } redraw(); } else { logErrorAndToast("Unsuccessful updateBeacon request: " + body); } } }; JSONObject json; try { json = beacon.toJson(); } catch (JSONException e) { logErrorAndToast("JSONException in creating update request", e); return; } client.updateBeacon(updateBeaconCallback, beacon.getBeaconName(), json); }