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.intuit.tank.okhttpclient.TankOkHttpClient.java
License:Open Source License
private void sendRequest(BaseRequest request, @Nonnull Request.Builder builder, String requestBody, String method) {// w ww .j av a 2 s. c o m String uri = null; long waitTime = 0L; try { setHeaders(request, builder, request.getHeaderInformation()); List<String> cookies = new ArrayList<String>(); if (((CookieManager) okHttpClient.getCookieHandler()).getCookieStore().getCookies() != null) { for (HttpCookie httpCookie : ((CookieManager) okHttpClient.getCookieHandler()).getCookieStore() .getCookies()) { cookies.add("REQUEST COOKIE: " + httpCookie.toString()); } } Request okRequest = builder.build(); uri = okRequest.uri().toString(); LOG.debug(request.getLogUtil().getLogMessage( "About to " + okRequest.method() + " request to " + uri + " with requestBody " + requestBody, LogEventType.Informational)); request.logRequest(uri, requestBody, okRequest.method(), request.getHeaderInformation(), cookies, false); Response response = okHttpClient.newCall(okRequest).execute(); long startTime = Long.parseLong(response.header("OkHttp-Sent-Millis")); long endTime = Long.parseLong(response.header("OkHttp-Sent-Millis")); // read response body byte[] responseBody = new byte[0]; // check for no content headers if (response.code() != 203 && response.code() != 202 && response.code() != 204) { try { responseBody = response.body().bytes(); } catch (Exception e) { LOG.warn("could not get response body: " + e); } } processResponse(responseBody, startTime, endTime, request, response.message(), response.code(), response.headers()); waitTime = endTime - startTime; } catch (Exception ex) { LOG.error(request.getLogUtil().getLogMessage( "Could not do " + method + " to url " + uri + " | error: " + ex.toString(), LogEventType.IO), ex); throw new RuntimeException(ex); } finally { if (method.equalsIgnoreCase("post") && request.getLogUtil().getAgentConfig().getLogPostResponse()) { LOG.info(request.getLogUtil() .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code " + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody() + " }", LogEventType.Informational)); } } if (waitTime != 0) { doWaitDueToLongResponse(request, waitTime, uri); } }
From source file:com.jaspersoft.android.jaspermobile.webview.intercept.okhttp.OkResponseMapper.java
License:Open Source License
public WebResponse toWebViewResponse(Response response) { final String mimeType = response.header(CONTENT_TYPE); final String encoding = response.header(CONTENT_ENCODING); final InputStream data = extractData(response); final int statusCode = response.code(); final String reasonPhrase = response.message(); final Map<String, String> responseHeaders = extractHeaders(response); return new WebResponse() { @Override// w w w . j a v a 2 s .c o m public String getMimeType() { return mimeType; } @Override public String getEncoding() { return encoding; } @Override public InputStream getData() { return data; } @Override public int getStatusCode() { return statusCode; } @Override public String getReasonPhrase() { return reasonPhrase; } @Override public Map<String, String> getResponseHeaders() { return responseHeaders; } }; }
From source file:com.joeyfrazee.nifi.reporting.HttpProvenanceReporter.java
License:Apache License
private void post(String json, String url) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder().url(url).post(body).build(); Response response = getHttpClient().newCall(request).execute(); getLogger().info("{} {} {}", new Object[] { Integer.valueOf(response.code()), response.message(), response.body().string() }); }
From source file:com.kubeiwu.easyandroid.easyhttp.core.retrofit.KOkHttpCall.java
License:Apache License
private Response<T> parseResponse(com.squareup.okhttp.Response rawResponse, com.squareup.okhttp.Request request) throws IOException { ResponseBody rawBody = rawResponse.body(); // rawResponse.r // 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(); int code = rawResponse.code(); if (code < 200 || code >= 300) { try {/*from w ww . j a v a 2 s.com*/ // Buffer the entire body to avoid future I/O. ResponseBody bufferedBody = Utils.readBodyToBytesIfNecessary(rawBody); return Response.error(bufferedBody, rawResponse); } finally { closeQuietly(rawBody); } } if (code == 204 || code == 205) { return Response.success(null, rawResponse); } ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody); try { T body; if (responseConverter instanceof GsonConverter) { GsonConverter<T> converter = (GsonConverter<T>) responseConverter; body = converter.fromBody(catchingBody, request); } else { body = responseConverter.fromBody(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; } }
From source file:com.leo.cattle.presentation.gcm.RegistrationIntentService.java
License:Open Source License
private void connectToApi(String token) { OkHttpClient okHttpClient = this.createClient(); final Request request = new Request.Builder() .url("http://13.76.128.53:8000/api/v1/me/tokens?gcmToken=" + token) .addHeader("X-MANADOR-KEY", AndroidApplication.sessionUser.getAccessToken()).get().build(); try {//from w w w. j a v a 2 s . c o m //String response = okHttpClient.newCall(request).execute().body().string(); Response httpResponse = okHttpClient.newCall(request).execute(); if (httpResponse.code() == 200) { //success Log.i(TAG, "GCM Registration Token: send to server" + token); } else { Log.i(TAG, "GCM Registration Token: send to server failed" + token); Log.i(TAG, "User Token" + AndroidApplication.sessionUser.getAccessToken()); } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.librelio.activity.StartupActivity.java
License:Apache License
private void loadAdvertisingImage() { client.setReadTimeout(2, TimeUnit.SECONDS); Request request = new Request.Builder().url(getAdvertisingImageURL()).build(); client.newCall(request).enqueue(new Callback() { @Override//from ww w.j a va 2s . c o m public void onResponse(Response response) throws IOException { if (response.code() == 200) { EasyTracker.getTracker() .sendView("Interstitial/" + FilenameUtils.getName(getAdvertisingImageURL())); byte[] bytes = response.body().bytes(); if (bytes != null) { adImage = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } loadAdvertisingLinkAndDisplayAdvertising(); } else { showMagazineAfterDelay(DEFAULT_ADV_DELAY); } response.body().close(); } @Override public void onFailure(Request request, Throwable throwable) { showMagazineAfterDelay(DEFAULT_ADV_DELAY); } }); }
From source file:com.librelio.activity.StartupActivity.java
License:Apache License
private void loadAdvertisingLinkAndDisplayAdvertising() { Request request = new Request.Builder().url(getAdvertisingLinkURL()).build(); client.newCall(request).enqueue(new Callback() { @Override//from ww w. j a va2 s. c o m public void onResponse(Response response) throws IOException { if (response.code() == 200) { PListXMLHandler handler = new PListXMLHandler(); PListXMLParser parser = new PListXMLParser(); parser.setHandler(handler); parser.parse(response.body().string()); PList list = ((PListXMLHandler) parser.getHandler()).getPlist(); if (list != null) { Dict dict = (Dict) list.getRootElement(); String delay = dict.getString(PLIST_DELAY).getValue().toString(); String link = dict.getString(PLIST_LINK).getValue().toString(); if (adImage != null) { runOnUiThread(new Runnable() { @Override public void run() { advertisingImage.setImageBitmap(adImage); if (isFirstImage) { applyRotation(0, 90); isFirstImage = !isFirstImage; } else { applyRotation(0, -90); isFirstImage = !isFirstImage; } } }); } setOnAdvertisingImageClickListener(link); showMagazineAfterDelay(Integer.valueOf(delay)); } } else { showMagazineAfterDelay(DEFAULT_ADV_DELAY); } response.body().close(); } @Override public void onFailure(Request request, Throwable throwable) { showMagazineAfterDelay(DEFAULT_ADV_DELAY); } }); }
From source file:com.liferay.mobile.android.auth.CookieSignIn.java
License:Open Source License
protected static Session parseResponse(Response response, String server, CookieManager cookieManager, CookieAuthentication authentication) throws Exception { if (response.code() == 500) { throw new AuthenticationException("Cookie invalid or empty"); }//w w w .ja v a 2 s. co m String body = response.body().string(); String authToken = parseAuthToken(body); String cookieHeader = getHttpCookies(cookieManager.getCookieStore()); if (Validator.isNotNull(cookieHeader)) { authentication.setAuthToken(authToken); authentication.setCookieHeader(cookieHeader); authentication.setLastCookieRefresh(System.currentTimeMillis()); return new SessionImpl(server, authentication); } else { throw new AuthenticationException("Cookie invalid or empty"); } }
From source file:com.liuguangqiang.asyncokhttp.RequestTask.java
License:Apache License
public void execute() { try {/* www. j a v a 2 s. c o m*/ Response response = mClient.newCall(mRequest).execute(); mResponseHandler.sendStart(); int code = response.code(); String responseString = "without response body"; if (response.body() != null) responseString = response.body().string(); if (response.isSuccessful()) mResponseHandler.sendSuccess(code, responseString); else mResponseHandler.sendFailure(code, responseString); } catch (IOException e) { String error = "unknown"; if (e.getMessage() != null) error = e.getMessage(); if (error.equals("Canceled")) mResponseHandler.sendCancel(); else mResponseHandler.sendFailure(0, error); } }
From source file:com.liulishuo.filedownloader.services.FileDownloadRunnable.java
License:Apache License
@Override public void run() { isPending = false;//from w w w. j av a 2s.co m isRunning = true; int retryingTimes = 0; Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadModel model = this.downloadModel; if (model == null) { FileDownloadLog.e(this, "start runnable but model == null?? %s", getId()); this.downloadModel = helper.find(getId()); if (this.downloadModel == null) { FileDownloadLog.e(this, "start runnable but downloadMode == null?? %s", getId()); return; } model = this.downloadModel; } if (model.getStatus() != FileDownloadStatus.pending) { FileDownloadLog.e(this, "start runnable but status err %s", model.getStatus()); // ??urlpath(????) ?? onError(new RuntimeException(String.format("start runnable but status err %s", model.getStatus()))); return; } // do { long soFar = 0; try { if (model.isCanceled()) { FileDownloadLog.d(this, "already canceled %d %d", model.getId(), model.getStatus()); break; } FileDownloadLog.d(FileDownloadRunnable.class, "start download %s %s", getId(), model.getUrl()); checkIsContinueAvailable(); Request.Builder headerBuilder = new Request.Builder().url(url); addHeader(headerBuilder); headerBuilder.tag(this.getId()); // ?cache?REST? headerBuilder.cacheControl(CacheControl.FORCE_NETWORK); Call call = client.newCall(headerBuilder.get().build()); Response response = call.execute(); final boolean isSucceedStart = response.code() == 200; final boolean isSucceedContinue = response.code() == 206 && isContinueDownloadAvailable; if (isSucceedStart || isSucceedContinue) { long total = downloadTransfer.getTotalBytes(); if (isSucceedStart || total == 0) { total = response.body().contentLength(); } if (isSucceedContinue) { soFar = downloadTransfer.getSoFarBytes(); FileDownloadLog.d(this, "add range %d %d", downloadTransfer.getSoFarBytes(), downloadTransfer.getTotalBytes()); } InputStream inputStream = null; RandomAccessFile accessFile = getRandomAccessFile(isSucceedContinue); try { inputStream = response.body().byteStream(); byte[] buff = new byte[BUFFER_SIZE]; maxNotifyBytes = maxNotifyCounts <= 0 ? -1 : total / maxNotifyCounts; updateHeader(response); onConnected(isSucceedContinue, soFar, total); do { int byteCount = inputStream.read(buff); if (byteCount == -1) { break; } accessFile.write(buff, 0, byteCount); //write buff soFar += byteCount; if (accessFile.length() < soFar) { // ?? throw new RuntimeException( String.format("file be changed by others when downloading %d %d", accessFile.length(), soFar)); } else { onProcess(soFar, total); } if (isCancelled()) { onPause(); return; } } while (true); if (soFar == total) { onComplete(total); // ? break; } else { throw new RuntimeException( String.format("sofar[%d] not equal total[%d]", soFar, total)); } } finally { if (inputStream != null) { inputStream.close(); } if (accessFile != null) { accessFile.close(); } } } else { throw new RuntimeException(String.format("response code error: %d", response.code())); } } catch (Throwable ex) { // TODO ??????? if (autoRetryTimes > retryingTimes++) { // retry onRetry(ex, retryingTimes, soFar); continue; } else { // error onError(ex); break; } } finally { isRunning = false; } } while (true); }