List of usage examples for com.squareup.okhttp Response code
int code
To view the source code for com.squareup.okhttp Response code.
Click Source Link
From source file:com.td.innovate.app.Activity.CaptureActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { progressDialog = ProgressDialog.show(this, "Getting results", "Processing image", true); if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { // Image captured and saved to fileUri specified in the Intent try { postImage(new Callback() { @Override/*w w w . j ava 2 s . c om*/ public void onFailure(Request request, IOException ioe) { // Something went wrong Log.e("Network error", "Error making image post request"); progressDialog.dismiss(); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String responseStr = response.body().string(); // Do what you want to do with the response. Log.d("response", "responseSTR: " + responseStr); System.out.println(responseStr); try { JSONObject myObject = new JSONObject(responseStr); final String token = myObject.getString("token"); checkForKeywords(token); } catch (JSONException je) { Log.e("Post response not JSON", je.getMessage()); } } else { // Request not successful System.out.println("Request not successful"); System.out.println(response.code()); System.out.println(response.message()); System.out.println(response.body().string()); progressDialog.dismiss(); } } }); } catch (Throwable e) { Log.e("Image call error", e.getMessage()); progressDialog.dismiss(); } } else if (resultCode == RESULT_CANCELED) { // User cancelled the image capture progressDialog.dismiss(); } else { // Image capture failed, advise user progressDialog.dismiss(); } } }
From source file:com.td.innovate.app.Activity.CaptureActivity.java
private void checkForKeywords(final String token) { this.runOnUiThread(new Runnable() { public void run() { progressDialog.setMessage("Identifying image"); final Handler h = new Handler(); final int delay = 3000; // milliseconds h.postDelayed(new Runnable() { public void run() { //do something try { getKeywords(token, new Callback() { @Override public void onFailure(Request request, IOException ioe) { // Something went wrong Log.e("Network error", "Error making token request"); progressDialog.dismiss(); }/*ww w .j a va 2s .c o m*/ @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String responseStr = response.body().string(); // Do what you want to do with the response. System.out.println(responseStr); try { JSONObject myObject = new JSONObject(responseStr); String status = myObject.getString("status"); if (status.equals("completed")) { keywords = myObject.getString("name"); gotKeywords = true; } } catch (JSONException je) { Log.e("Get response not JSON", je.getMessage()); progressDialog.dismiss(); } } else { // Request not successful System.out.println("Request not successful"); System.out.println(response.code()); System.out.println(response.message()); System.out.println(response.body().string()); progressDialog.dismiss(); } } }); } catch (Throwable e) { Log.e("Token call error", e.getMessage()); progressDialog.dismiss(); } if (!gotKeywords) { h.postDelayed(this, delay); } else { System.out.println(keywords); if (progressDialog != null) { progressDialog.dismiss(); } Intent intent = new Intent(context, MainViewPagerActivity.class); intent.putExtra("keywords", keywords); intent.putExtra("barcode", "null"); startActivity(intent); } } }, delay); } }); }
From source file:com.teddoll.movies.reciever.MovieSync.java
License:Apache License
public static String[] loadCachedData(final OkHttpClient client) { String pop = "[]"; String rate = "[]"; String genre = "[]"; Request popRequest = new Request.Builder().cacheControl(new CacheControl.Builder().onlyIfCached().build()) .url(POP_URL).addHeader("Accept", "application/json").build(); try {/*from w w w . j a v a 2 s . c om*/ Response forcePopCacheResponse = client.newCall(popRequest).execute(); if (forcePopCacheResponse.code() != 504) { JSONObject json = new JSONObject(forcePopCacheResponse.body().string()); JSONArray array = json.optJSONArray("results"); pop = array != null ? array.toString() : null; } } catch (IOException | JSONException e) { e.printStackTrace(); } Request rateRequest = new Request.Builder().cacheControl(new CacheControl.Builder().onlyIfCached().build()) .url(RATE_URL).addHeader("Accept", "application/json").build(); try { Response forceRateCacheResponse = client.newCall(rateRequest).execute(); if (forceRateCacheResponse.code() != 504) { JSONObject json = new JSONObject(forceRateCacheResponse.body().string()); JSONArray array = json.optJSONArray("results"); rate = array != null ? array.toString() : null; } } catch (IOException | JSONException e) { e.printStackTrace(); } Request genreRequest = new Request.Builder().cacheControl(new CacheControl.Builder().onlyIfCached().build()) .url(GENRE_URL).addHeader("Accept", "application/json").build(); try { Response forceGenreCacheResponse = client.newCall(genreRequest).execute(); if (forceGenreCacheResponse.code() != 504) { JSONObject json = new JSONObject(forceGenreCacheResponse.body().string()); JSONArray array = json.optJSONArray("genres"); genre = array != null ? array.toString() : null; } } catch (IOException | JSONException e) { e.printStackTrace(); } return new String[] { pop, rate, genre }; }
From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java
License:Apache License
public JsonElement request(String path, String requestBody, HttpVerb verb) throws RestApiException { try {//from w ww . ja v a 2 s. com Response response = doRest(path, requestBody, verb); if (response.code() == 403 && loginCache.getGerritAuthOptional().isPresent()) { // handle expired sessions: try again with a fresh login loginCache.invalidate(); response = doRest(path, requestBody, verb); } checkStatusCode(response); InputStream resp = response.body().byteStream(); JsonElement ret = parseResponse(resp); if (ret.isJsonNull()) { throw new RestApiException("Unexpectedly empty response."); } return ret; } catch (IOException e) { throw new RestApiException("Request failed.", e); } }
From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java
License:Apache License
private Optional<String> extractGerritAuth(Response loginResponse) throws IOException { if (loginResponse.code() != 401) { Optional<HttpCookie> gerritAccountCookie = findGerritAccountCookie(); if (gerritAccountCookie.isPresent()) { // TODO /*Matcher matcher = GERRIT_AUTH_PATTERN.matcher(EntityUtils.toString(loginResponse.getEntity(), Consts.UTF_8)); if (matcher.find()) {// w w w .j a v a2 s .co m return Optional.of(matcher.group(1)); }*/ } } return Optional.absent(); }
From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java
License:Apache License
private void checkStatusCode(Response response) throws HttpStatusException, IOException { int code = response.code(); switch (code) { case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: case HttpStatus.SC_ACCEPTED: case HttpStatus.SC_NO_CONTENT: return;/* w w w . j ava2 s .c o m*/ case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_PAYMENT_REQUIRED: case HttpStatus.SC_FORBIDDEN: default: String body = "<empty>"; body = CharStreams.toString(response.body().charStream()).trim(); String message = String.format("Request not successful. Message: %s. Status-Code: %s. Content: %s.", response.message(), response.code(), body); throw new HttpStatusException(response.code(), response.message(), message); } }
From source file:com.weather.hackathon.model.LayersFetcher.java
License:Open Source License
/** * Requests a new set of available tiles in the background. A successful load will notify the * {@link LayersResultListener} if one has been {@link #setLayersResultListener(LayersResultListener) set}. * * <p/> Only successful fetches are reported. Errors are logged and ignored. Listener's callback * {@link LayersResultListener#onLayersReceived(Collection) method} will be called on the same thread that * created this instance./*from ww w . j a v a 2 s. c o m*/ * * <p/> The layers fetched will contain the {@link Layer#getTimestamp() timestamp} of the newest tiles for * that layer. */ public void fetchAsync() { Request request = new Request.Builder().url("http://hackathon.weather.com/Maps/jsonserieslist.do").build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.e(TAG, "Unable to retrieve list of layers", e); } @Override public void onResponse(Response response) throws IOException { try { if (response.isSuccessful()) { final String json = response.body().string(); final Collection<Layer> layers = Layers.parseJson(json); handler.post(new Runnable() { @Override public void run() { if (layersResultListener != null) { layersResultListener.onLayersReceived(layers); } } }); } else { Log.e(TAG, "Error request list of layers. statusCode=" + response.code()); } } catch (JsonSyntaxException e) { Log.e(TAG, "Unable to parse list of layers", e); } } }); }
From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java
License:Open Source License
@Override public void checkConnection() { try {// ww w. jav a 2 s. co m LOG.info("Checking connection to {}", serverUrl); Request request = createRequestFor(API_CONNECTION_CHECK); Response response = client.newCall(request).execute(); switch (response.code()) { case 200: return; case 401: throw new AuthenticationException(String.format( "User '%s' and the supplied password are unable to log in", credentials.getUsername())); case 402: throw new PaymentRequiredException("The XL TestView server does not have a valid license"); case 404: throw new ConnectionException("URL is invalid or server is not running"); default: throw new IllegalStateException("Unknown error. Status code: " + response.code() + ". Response message: " + response.toString()); } } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java
License:Open Source License
@Override public void uploadTestRun(String testSpecificationId, FilePath workspace, String includes, String excludes, Map<String, Object> metadata, PrintStream logger) throws IOException, InterruptedException { if (testSpecificationId == null || testSpecificationId.isEmpty()) { throw new IllegalArgumentException( "No test specification id specified. Does the test specification still exist in XL TestView?"); }/*from w w w . j a v a 2 s. c o m*/ try { logInfo(logger, format("Collecting files from '%s' using include pattern: '%s' and exclude pattern '%s'", workspace.getRemote(), includes, excludes)); DirScanner scanner = new DirScanner.Glob(includes, excludes); ObjectMapper objectMapper = new ObjectMapper(); RequestBody body = new MultipartBuilder().type(MultipartBuilder.MIXED) .addPart(RequestBody.create(MediaType.parse(APPLICATION_JSON_UTF_8), objectMapper.writeValueAsString(metadata))) .addPart(new ZipRequestBody(workspace, scanner, logger)).build(); Request request = new Request.Builder() .url(createSensibleURL(API_IMPORT + "/" + testSpecificationId, serverUrl)) .header("User-Agent", getUserAgent()).header("Accept", APPLICATION_JSON_UTF_8) .header("Authorization", createCredentials()).header("Transfer-Encoding", "chunked").post(body) .build(); Response response = client.newCall(request).execute(); ObjectMapper mapper = createMapper(); ImportError importError; switch (response.code()) { case 200: logInfo(logger, "Sent data successfully"); return; case 304: logWarn(logger, "No new results were detected. Nothing was imported."); throw new IllegalStateException("No new results were detected. Nothing was imported."); case 400: importError = mapper.readValue(response.body().byteStream(), ImportError.class); throw new IllegalStateException(importError.getMessage()); case 401: throw new AuthenticationException(String.format( "User '%s' and the supplied password are unable to log in", credentials.getUsername())); case 402: throw new PaymentRequiredException("The XL TestView server does not have a valid license"); case 404: throw new ConnectionException("Cannot find test specification '" + testSpecificationId + ". Please check if the XL TestView server is " + "running and the test specification exists."); case 422: logWarn(logger, "Unable to process results."); logWarn(logger, "Are you sure your include/exclude pattern provides all needed files for the test tool?"); importError = mapper.readValue(response.body().byteStream(), ImportError.class); throw new IllegalStateException(importError.getMessage()); default: throw new IllegalStateException("Unknown error. Status code: " + response.code() + ". Response message: " + response.toString()); } } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } catch (IOException e) { e.printStackTrace(); LOG.warn("I/O error uploading test run data to {} {}\n{}", serverUrl.toString(), e.toString(), e); throw new IOException( "I/O error uploading test run data to " + serverUrl.toString() + " " + e.toString(), e); } }
From source file:com.xing.api.CallSpec.java
License:Apache License
/** Parsers the OkHttp raw response and returns an response ready to be consumed by the caller. */ @SuppressWarnings("MagicNumber") // These codes are specific to this method and to the http protocol. private Response<RT, ET> parseResponse(com.squareup.okhttp.Response rawResponse) throws IOException { ResponseBody rawBody = rawResponse.body(); // Remove the body's source (the only stateful object) so we can pass the response along. rawResponse = rawResponse.newBuilder() .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())).build(); ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody); int code = rawResponse.code(); if (code < 200 || code >= 300) { try {/* w w w .ja v a 2 s. c om*/ // Buffer the entire body to avoid future I/O. ET errorBody = parseBody(errorType, catchingBody); return Response.error(errorBody, rawResponse); } catch (RuntimeException e) { // If the underlying source threw an exception, propagate that, rather than indicating it was // a runtime exception. catchingBody.throwIfCaught(); throw e; } finally { closeQuietly(catchingBody); } } // No need to parse the response body since the response should not contain a body. if (code == 204 || code == 205) { return Response.success(null, rawResponse); } try { RT body = parseBody(responseType, catchingBody); return Response.success(body, rawResponse); } catch (RuntimeException e) { // If the underlying source threw an exception, propagate that, rather than indicating it was // a runtime exception. catchingBody.throwIfCaught(); throw e; } finally { closeQuietly(catchingBody); } }