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.cinchapi.concourse.http.RestWriteTest.java
License:Apache License
@Test public void testInsertKeyAsValueInNewRecord() { String key = TestData.getSimpleString(); Object value = TestData.getObject(); String strValue = prepareForJsonImport(value); Response resp = post("/{0}", strValue, key); long record = bodyAsJava(resp, TypeToken.get(Long.class)); Assert.assertEquals(200, resp.code()); Assert.assertEquals(value, client.get(key, record)); }
From source file:com.cml.rx.android.api.HttpLoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE) { return chain.proceed(request); }//from w ww . ja v a2 s .c o m boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; RequestBody requestBody = request.body(); boolean hasRequestBody = requestBody != null; Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1; String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol; if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(requestStartMessage); if (logHeaders) { if (hasRequestBody) { // Request body headers are only present when installed as a // network interceptor. Force // them to be included (when available) so there values are // known. if (requestBody.contentType() != null) { logger.log("Content-Type: " + requestBody.contentType()); } if (requestBody.contentLength() != -1) { logger.log("Content-Length: " + requestBody.contentLength()); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); // Skip headers from the request body as they are explicitly // logged above. if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { logger.log(name + ": " + headers.value(i)); } } if (!logBody || !hasRequestBody) { logger.log("--> END " + request.method()); } else if (bodyEncoded(request.headers())) { logger.log("--> END " + request.method() + " (encoded body omitted)"); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } logger.log(""); if (isPlaintext(buffer)) { logger.log(buffer.readString(charset)); logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } else { logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)"); } } } long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (Exception e) { logger.log("<-- HTTP FAILED: " + e); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length"; logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { logger.log(headers.name(i) + ": " + headers.value(i)); } if (!logBody || !HttpEngine.hasBody(response)) { logger.log("<-- END HTTP"); } else if (bodyEncoded(response.headers())) { logger.log("<-- END HTTP (encoded body omitted)"); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { try { charset = contentType.charset(UTF8); } catch (UnsupportedCharsetException e) { logger.log(""); logger.log("Couldn't decode the response body; charset is likely malformed."); logger.log("<-- END HTTP"); return response; } } if (!isPlaintext(buffer)) { logger.log(""); logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)"); return response; } if (contentLength != 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } logger.log("<-- END HTTP (" + buffer.size() + "-byte body)"); } } return response; }
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 {/*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 {} ({}), {} 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.backup.BackupService.java
License:Apache License
private void uploadBackup(File backup) throws IOException { Request request = new Request.Builder().url(URL_CREATE_BACKUP).post(RequestBody.create(JSON, "{}")).build(); Response response = OKHTTP_CLIENT.newCall(request).execute(); if (response.code() == 201) { String backupURL = response.header("Location"); request = new Request.Builder().url(backupURL + RESOURCE_DATASET).put(RequestBody.create(ZIP, backup)) .build();// w w w . jav a 2 s. c o m response = OKHTTP_CLIENT.newCall(request).execute(); if (response.code() == 201) { String datasetURL = response.header("Location"); SharedPreferences prefs = getSharedPreferences(getClass().getName(), Context.MODE_PRIVATE); prefs.edit().putString(PREF_LAST_BACKUP_DATASET, datasetURL).commit(); } else { Log.e(getClass().getSimpleName(), "Unsuccessful request to upload backup"); } } else { Log.e(getClass().getSimpleName(), "Unsuccessful request to create backup"); } }
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 {/*w w w. j a v a 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; }
From source file:com.cuddlesoft.norilib.service.ServiceTypeDetectionService.java
@Override protected void onHandleIntent(Intent intent) { // Extract SearchClient.Settings from the received Intent. final Uri uri = Uri.parse(intent.getStringExtra(ENDPOINT_URL)); final Intent broadcastIntent = new Intent(ACTION_DONE); if (uri.getHost() == null || uri.getScheme() == null) { // The URL supplied is invalid. sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_INVALID_URL)); return;/*from w ww . j a v a 2s. c o m*/ } // Create the HTTP client. final OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setConnectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS); okHttpClient.setReadTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS); // Iterate over supported URI schemes for given URL. for (String uriScheme : (TLS_SUPPORT.contains(uri.getHost()) ? URI_SCHEMES_PREFER_SSL : URI_SCHEMES)) { String baseUri = uriScheme + uri.getHost(); // Iterate over each endpoint path. for (Map.Entry<SearchClient.Settings.APIType, String> entry : API_ENDPOINT_PATHS.entrySet()) { // Create a HTTP request object. final Request request = new Request.Builder().url(baseUri + entry.getValue()).build(); try { // Fetch response. final Response response = okHttpClient.newCall(request).execute(); // Make sure the response code was OK and that the HTTP client wasn't redirected along the way. if (response.code() == HttpStatus.SC_OK && response.priorResponse() == null) { // Found an API endpoint. broadcastIntent.putExtra(RESULT_CODE, RESULT_OK); broadcastIntent.putExtra(ENDPOINT_URL, baseUri); broadcastIntent.putExtra(API_TYPE, entry.getKey().ordinal()); sendBroadcast(broadcastIntent); return; } } catch (IOException e) { // Network error. Notify the listeners and return. sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_NETWORK)); return; } } } // End of the loop was reached without finding an API endpoint. Send error code to the BroadcastReceiver. sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_NO_API)); }
From source file:com.datastore_android_sdk.okhttp.OkHttpStack.java
License:Open Source License
private URLHttpResponse responseFromConnection(Response okHttpResponse) throws IOException { URLHttpResponse response = new URLHttpResponse(); //contentStream int responseCode = okHttpResponse.code(); if (responseCode == -1) { throw new IOException("Could not retrieve response code from HttpUrlConnection."); }/* ww w . ja v a 2s. c om*/ response.setResponseCode(responseCode); response.setResponseMessage(okHttpResponse.message()); response.setContentStream(okHttpResponse.body().byteStream()); response.setContentLength(okHttpResponse.body().contentLength()); response.setContentEncoding(okHttpResponse.header("Content-Encoding")); if (okHttpResponse.body().contentType() != null) { response.setContentType(okHttpResponse.body().contentType().type()); } //header HashMap<String, String> headerMap = new HashMap<>(); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { headerMap.put(name, value); } } response.setHeaders(headerMap); return response; }
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 ww . ja v a 2 s .c om*/ * <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.digi.wva.internal.HttpClient.java
License:Mozilla Public License
/** * Log information of OkHttp Response objects * * <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 ww w. j av a 2s . c om * <a href="http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode" target="_blank">see StackOverflow question.</a> * </p> * @param response the HTTP response object to log */ protected void logResponse(Response response) { if (!doLogging) { // Logging is disabled - do nothing. return; } Request request = response.request(); StringBuilder log = new StringBuilder(); log.append( // e.g. <-- 200 GET /ws/hw/leds/foo String.format("\u2190 %d %s %s", response.code(), request.method(), request.urlString())); // Add on lines tracking any redirects that occurred. Response prior = response.priorResponse(); if (prior != null) { // Call out that there were prior responses. log.append(" (prior responses below)"); // Add a line to the log message for each prior response. // (For most if not all responses, there will likely be just one.) do { log.append(String.format("\n... prior response: %d %s %s", prior.code(), prior.request().method(), prior.request().urlString())); // If this is a redirect, log the URL we're being redirected to. if (prior.isRedirect()) { log.append(", redirecting to "); log.append(prior.header("Location", "[no Location header found?!]")); } prior = prior.priorResponse(); } while (prior != null); } Log.i(TAG, log.toString()); }
From source file:com.digitalglobe.iipfoundations.productservice.orderservice.OrderService.java
/** * /*from w w w . j a v a 2 s . co m*/ * @param cat_id * @param auth_token * @return - the order_id * @throws IOException * @throws OrderServiceException */ public static String order1b(String cat_id, String auth_token) throws IOException, OrderServiceException { String request = generateOrder1bRequestBody(cat_id); System.out.println(request); MediaType mediaType = MediaType.parse("application/json"); RequestBody request_body = RequestBody.create(mediaType, request); //Properties gbdx = GBDxCredentialManager.getGBDxCredentials(); Request search_request = new Request.Builder().url("http://orders.iipfoundations.com/order/v1") .post(request_body).addHeader("content-type", "application/json") .addHeader("authorization", "Basic " + auth_token).addHeader("username", username) .addHeader("password", password).build(); OkHttpClient client = new OkHttpClient(); System.out.println(search_request.toString()); Response response = client.newCall(search_request).execute(); if (200 == response.code()) { String body = response.body().string(); System.out.println(body); JSONObject obj = new JSONObject(body); JSONArray orders = obj.getJSONArray("orders"); JSONObject order = orders.getJSONObject(0); int id = order.getInt("id"); return Integer.toString(id); } else { System.out.println(response.body().string()); logger.error(response.message()); throw new OrderServiceException(response.message()); } }