Java Code Examples for com.squareup.okhttp.Response#isSuccessful()
The following examples show how to use
com.squareup.okhttp.Response#isSuccessful() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SimpleRequest.java From Auth0.Android with MIT License | 6 votes |
@Override public void onResponse(Response response) { if (!response.isSuccessful()) { postOnFailure(parseUnsuccessfulResponse(response)); return; } ResponseBody body = response.body(); try { Reader charStream = body.charStream(); T payload = getAdapter().fromJson(charStream); postOnSuccess(payload); } catch (IOException e) { final Auth0Exception auth0Exception = new Auth0Exception("Failed to parse response to request to " + url, e); postOnFailure(getErrorBuilder().from("Failed to parse a successful response", auth0Exception)); } finally { closeStream(body); } }
Example 2
Source File: JokeParser.java From JianDan_OkHttp with Apache License 2.0 | 6 votes |
@Nullable public ArrayList<Joke> parse(Response response) { code = wrapperCode(response.code()); if (!response.isSuccessful()) return null; try { String jsonStr = response.body().string(); jsonStr = new JSONObject(jsonStr).getJSONArray("comments").toString(); return (ArrayList<Joke>) JSONParser.toObject(jsonStr, new TypeToken<ArrayList<Joke>>() { }.getType()); } catch (Exception e) { e.printStackTrace(); return null; } }
Example 3
Source File: AuthCookie.java From utexas-utilities with Apache License 2.0 | 6 votes |
/** * Executes a login request with the AuthCookie's OkHttpClient. This should only be called * when persistent login is activated. * @param request Request to execute * @return true if the cookie was set successfully, false if the cookie was not set * @throws IOException */ protected boolean performLogin(Request request) throws IOException { Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Bad response code: " + response + " during login."); } response.body().close(); CookieManager cm = (CookieManager) CookieHandler.getDefault(); List<HttpCookie> cookies = cm.getCookieStore().getCookies(); for (HttpCookie cookie : cookies) { String cookieVal = cookie.getValue(); if (cookie.getName().equals(authCookieKey)) { setAuthCookieVal(cookieVal); return true; } } return false; }
Example 4
Source File: ZalyHttpClient.java From openzaly with Apache License 2.0 | 6 votes |
public byte[] postString(String url, String json) throws IOException { ResponseBody body = null; try { RequestBody postBody = RequestBody.create(JSON, json); Request request = new Request.Builder().url(url).post(postBody).build(); Response response = httpClient.newCall(request).execute(); if (response.isSuccessful()) { body = response.body(); byte[] res = body.bytes(); return res; } else { logger.error("http post error.{}", response.message()); } } finally { if (body != null) { body.close(); } } return null; }
Example 5
Source File: SwaggerHubClient.java From swaggerhub-maven-plugin with Apache License 2.0 | 6 votes |
public Optional<Response> saveIntegrationPluginOfType(SaveSCMPluginConfigRequest saveSCMPluginConfigRequest) throws JsonProcessingException { HttpUrl httpUrl = getSaveIntegrationPluginConfigURL(saveSCMPluginConfigRequest); MediaType mediaType = MediaType.parse("application/json"); Request httpRequest = buildPutRequest(httpUrl, mediaType, saveSCMPluginConfigRequest.getRequestBody()); try { Response response = client.newCall(httpRequest).execute(); if(!response.isSuccessful()){ log.error(String.format("Error when attempting to save %s plugin integration for API %s version %s", saveSCMPluginConfigRequest.getScmProvider(), saveSCMPluginConfigRequest.getApi(),saveSCMPluginConfigRequest.getVersion())); log.error("Error response: "+response.body().string()); response.body().close(); } return Optional.ofNullable(response); } catch (IOException e) { log.error(String.format("Error when attempting to save %s plugin integration for API %s. Error message %s", saveSCMPluginConfigRequest.getScmProvider(), saveSCMPluginConfigRequest.getApi(), e.getMessage())); return Optional.empty(); } }
Example 6
Source File: GoogleSignInDialogFragment.java From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public void onResponse(Response response) throws IOException { try { String body = response.body().string(); final JSONObject jsonResponse = new JSONObject(body); Log.v(Utils.TAG, jsonResponse.toString()); if (!response.isSuccessful()) { } else { final String access_token = jsonResponse.getString("access_token"); if(jsonResponse.has("refresh_token")) { final String refresh_token = jsonResponse.getString("refresh_token"); saveAccessToken(access_token, refresh_token); } else { saveNewAccessToken(access_token); } } } catch (JSONException e) { e.printStackTrace(); } }
Example 7
Source File: ZalyHttpClient.java From wind-im with Apache License 2.0 | 6 votes |
public byte[] get(String url) throws Exception { ResponseBody body = null; try { Request request = new Request.Builder().url(url).build(); Response response = httpClient.newCall(request).execute(); if (response.isSuccessful()) { body = response.body(); byte[] res = body.bytes(); return res; } else { logger.error("http get url={} error.{}", url, response.message()); } } finally { if (body != null) { body.close(); } } return null; }
Example 8
Source File: SwaggerHubClient.java From swaggerhub-maven-plugin with Apache License 2.0 | 6 votes |
public Optional<Response> saveDefinition(SwaggerHubRequest swaggerHubRequest) { HttpUrl httpUrl = getUploadUrl(swaggerHubRequest); MediaType mediaType = MediaType.parse("application/" + swaggerHubRequest.getFormat()); Request httpRequest = buildPostRequest(httpUrl, mediaType, swaggerHubRequest.getSwagger()); try { Response response = client.newCall(httpRequest).execute(); if(!response.isSuccessful()){ log.error(String.format("Error when attempting to save API %s version %s", swaggerHubRequest.getApi(), swaggerHubRequest.getVersion())); log.error("Error response: "+response.body().string()); response.body().close(); } return Optional.ofNullable(response); } catch (IOException e) { log.error(String.format("Error when attempting to save API %s. Error message %s", swaggerHubRequest.getApi(), e.getMessage())); return Optional.empty(); } }
Example 9
Source File: WebAppHelper.java From xDrip with GNU General Public License v3.0 | 6 votes |
@Override protected Integer doInBackground(String... url) { try { Log.d(TAG, "Processing URL: " + url[0]); Request request = new Request.Builder() .header("User-Agent", "Mozilla/5.0 (jamorham)") .header("Connection", "close") .url(url[0]) .build(); client.setConnectTimeout(15, TimeUnit.SECONDS); client.setReadTimeout(30, TimeUnit.SECONDS); client.setWriteTimeout(30, TimeUnit.SECONDS); final Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); body = response.body().bytes(); } catch (Exception e) { Log.d(TAG, "Exception in background task: " + e.toString()); } return body.length; }
Example 10
Source File: QiitaBaseApi.java From Qiitanium with MIT License | 6 votes |
protected <T> ResponseDto<T> execute(Request.Builder request, Type type) { try { final Response response = execute(request); if (!response.isSuccessful()) { throw new WebAccessException(response.code(), fetchErrorMessage(response)); } final ResponseDto<T> dto = new ResponseDto<T>(); dto.body = objectify(response, type); dto.page = fetchPagenationHeader(response); return dto; } catch (IOException ioe) { throw new DataAccessException(ioe); } }
Example 11
Source File: Push4FreshCommentParser.java From JianDan_OkHttp with Apache License 2.0 | 6 votes |
@Nullable public Boolean parse(Response response) { code = wrapperCode(response.code()); if (!response.isSuccessful()) return null; try { JSONObject resultObj = new JSONObject(response.body().string()); String result = resultObj.optString("status"); if (result.equals("ok")) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); return false; } }
Example 12
Source File: HttpApiBase.java From iview-android-tv with MIT License | 6 votes |
private ResponseBody fetchFromNetwork(Uri url, int staleness) { Request.Builder builder = new Request.Builder(); builder.url(url.toString()); if (staleness > 0) { builder.cacheControl(allowStaleCache(staleness)); } Request request = builder.build(); client.setConnectTimeout(10, TimeUnit.SECONDS); client.setReadTimeout(60, TimeUnit.SECONDS); Log.d(TAG, "Requesting URL:" + request.urlString()); try { Response response = client.newCall(request).execute(); if (response.cacheResponse() != null) { Log.d(TAG, "Cached response [" + response.code() + "]:" + request.urlString()); } else { Log.d(TAG, "Network response [" + response.code() + "]:" + request.urlString()); } if (response.isSuccessful()) { return response.body(); } } catch (IOException e) { e.printStackTrace(); } return null; }
Example 13
Source File: ZalyHttpClient.java From wind-im with Apache License 2.0 | 6 votes |
public byte[] postString(String url, String json) throws IOException { ResponseBody body = null; try { RequestBody postBody = RequestBody.create(JSON, json); Request request = new Request.Builder().url(url).post(postBody).build(); Response response = httpClient.newCall(request).execute(); if (response.isSuccessful()) { body = response.body(); byte[] res = body.bytes(); return res; } else { logger.error("http post error.{}", response.message()); } } finally { if (body != null) { body.close(); } } return null; }
Example 14
Source File: WXWebsocketBridge.java From weex with Apache License 2.0 | 5 votes |
@Override public void onSuccess(Response response) { if(response.isSuccessful()){ WXSDKManager.getInstance().postOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(WXEnvironment.sApplication,"Has switched to DEBUG mode, you can see the DEBUG information on the browser!",Toast.LENGTH_SHORT).show(); } },0); } }
Example 15
Source File: HttpClient.java From openzaly with Apache License 2.0 | 5 votes |
static String postJson(String url, String json) throws IOException { MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody postBody = RequestBody.create(JSON, json); Request request = new Request.Builder().url(url).post(postBody).build(); Response response = client.newCall(request).execute(); System.out.println("post postJson response =" + response.isSuccessful()); if (response.isSuccessful()) { return response.body().toString(); } else { System.out.println("http post failed"); throw new IOException("post json Unexpected code " + response); } }
Example 16
Source File: Trakt.java From Mizuu with Apache License 2.0 | 5 votes |
public static JSONArray getTvShowLibrary(Context c, int type) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c); String username = settings.getString(TRAKT_USERNAME, "").trim(); String password = settings.getString(TRAKT_PASSWORD, ""); if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) return new JSONArray(); try { String url = ""; if (type == WATCHED) { url = "http://api.trakt.tv/user/library/shows/watched.json/" + getApiKey(c) + "/" + username; } else if (type == RATINGS) { url = "http://api.trakt.tv/user/ratings/shows.json/" + getApiKey(c) + "/" + username + "/love"; } else if (type == COLLECTION) { url = "http://api.trakt.tv/user/library/shows/collection.json/" + getApiKey(c) + "/" + username; } Request request = MizLib.getTraktAuthenticationRequest(url, username, password); Response response = MizuuApplication.getOkHttpClient().newCall(request).execute(); if (response.isSuccessful()) return new JSONArray(response.body().string()); return new JSONArray(); } catch (Exception e) { return new JSONArray(); } }
Example 17
Source File: Trakt.java From Mizuu with Apache License 2.0 | 5 votes |
public static boolean moviesWatchlist(List<MediumMovie> movies, Context c) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c); String username = settings.getString(TRAKT_USERNAME, "").trim(); String password = settings.getString(TRAKT_PASSWORD, ""); if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || movies.size() == 0) return false; try { JSONObject json = new JSONObject(); json.put("username", username); json.put("password", password); JSONArray array = new JSONArray(); int count = movies.size(); for (int i = 0; i < count; i++) { JSONObject jsonMovie = new JSONObject(); jsonMovie.put("tmdb_id", movies.get(i).getTmdbId()); jsonMovie.put("year", movies.get(i).getReleaseYear()); jsonMovie.put("title", movies.get(i).getTitle()); array.put(jsonMovie); } json.put("movies", array); Request request = MizLib.getJsonPostRequest((movies.get(0).toWatch() ? "http://api.trakt.tv/movie/watchlist/" : "http://api.trakt.tv/movie/unwatchlist/") + getApiKey(c), json); Response response = MizuuApplication.getOkHttpClient().newCall(request).execute(); return response.isSuccessful(); } catch (Exception e) { return false; } }
Example 18
Source File: HttpClient.java From wind-im with Apache License 2.0 | 5 votes |
static String postKV(String url) throws IOException { RequestBody formBody = new FormEncodingBuilder().add("platform", "android").add("name", "bug").build(); Request request = new Request.Builder().url(url).post(formBody).build(); Response response = client.newCall(request).execute(); System.out.println("post KV response =" + response.isSuccessful()); if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } }
Example 19
Source File: Trakt.java From Mizuu with Apache License 2.0 | 5 votes |
public static boolean movieFavorite(List<Movie> movies, Context c) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c); String username = settings.getString(TRAKT_USERNAME, "").trim(); String password = settings.getString(TRAKT_PASSWORD, ""); if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || movies.size() == 0) return false; try { JSONObject json = new JSONObject(); json.put("username", username); json.put("password", password); JSONArray array = new JSONArray(); int count = movies.size(); for (int i = 0; i < count; i++) { JSONObject jsonMovie = new JSONObject(); jsonMovie.put("imdb_id", movies.get(i).getImdbId()); jsonMovie.put("tmdb_id", movies.get(i).getTmdbId()); jsonMovie.put("year", movies.get(i).getReleaseYear()); jsonMovie.put("title", movies.get(i).getTitle()); jsonMovie.put("rating", movies.get(i).isFavourite() ? "love" : "unrate"); array.put(jsonMovie); } json.put("movies", array); Request request = MizLib.getJsonPostRequest("http://api.trakt.tv/rate/movies/" + getApiKey(c), json); Response response = MizuuApplication.getOkHttpClient().newCall(request).execute(); return response.isSuccessful(); } catch (Exception e) { return false; } }
Example 20
Source File: CommentCountsParser.java From JianDan_OkHttp with Apache License 2.0 | 5 votes |
@Override public ArrayList<CommentNumber> parse(Response response) { code = wrapperCode(response.code()); if (!response.isSuccessful()) return null; try { String body = response.body().string(); JSONObject jsonObject = new JSONObject(body).getJSONObject("response"); String[] comment_IDs = response.request().urlString().split("\\=")[1].split("\\,"); ArrayList<CommentNumber> commentNumbers = new ArrayList<>(); for (String comment_ID : comment_IDs) { if (!jsonObject.isNull(comment_ID)) { CommentNumber commentNumber = new CommentNumber(); commentNumber.setComments(jsonObject.getJSONObject(comment_ID).getInt(CommentNumber.COMMENTS)); commentNumber.setThread_id(jsonObject.getJSONObject(comment_ID).getString(CommentNumber.THREAD_ID)); commentNumber.setThread_key(jsonObject.getJSONObject(comment_ID).getString(CommentNumber.THREAD_KEY)); commentNumbers.add(commentNumber); } else { //可能会出现没有对应id的数据的情况,为了保证条数一致,添加默认数据 commentNumbers.add(new CommentNumber("0", "0", 0)); } } return commentNumbers; } catch (Exception e) { e.printStackTrace(); return null; } }