List of usage examples for com.squareup.okhttp ResponseBody contentLength
public abstract long contentLength() throws IOException;
From source file:com.hippo.network.DownloadClient.java
License:Apache License
public static boolean execute(DownloadRequest request) { OnDownloadListener listener = request.mListener; OkHttpClient okHttpClient = request.mOkHttpClient; UniFile uniFile = null;//from ww w. j av a 2s. c o m OutputStreamPipe osPipe = null; try { Call call = okHttpClient.newCall(new GoodRequestBuilder(request.mUrl).build()); request.mCall = call; // Listener if (listener != null) { listener.onStartDownloading(); } Response response = call.execute(); ResponseBody body = response.body(); // Check response code int responseCode = response.code(); if (responseCode >= 400) { throw new ResponseCodeException(responseCode); } osPipe = request.mOSPipe; if (osPipe == null) { String extension; String name; String dispositionFilename = getFilenameFromContentDisposition( response.header("Content-Disposition")); if (dispositionFilename != null) { name = FileUtils.getNameFromFilename(dispositionFilename); extension = FileUtils.getExtensionFromFilename(dispositionFilename); } else { name = Utilities.getNameFromUrl(request.mUrl); extension = Utilities.getExtensionFromMimeType(response.header("Content-Type")); if (extension == null) { extension = MimeTypeMap.getFileExtensionFromUrl(request.mUrl); } } String filename; if (listener != null) { filename = listener.onFixname(name, extension, request.mFilename); } else { filename = request.mFilename; } request.mFilename = filename; // Use Temp filename uniFile = request.mDir.createFile(FileUtils.ensureFilename(filename + ".download")); if (uniFile == null) { // Listener if (listener != null) { listener.onFailed(new IOException("Can't create file " + filename)); } return false; } osPipe = new UniFileOutputStreamPipe(uniFile); } osPipe.obtain(); long contentLength = body.contentLength(); // Listener if (listener != null) { listener.onConnect(contentLength); } long receivedSize = transferData(body.byteStream(), osPipe.open(), listener); if (contentLength > 0 && contentLength != receivedSize) { throw new IOException( "contentLength is " + contentLength + ", but receivedSize is " + receivedSize); } // Rename if (uniFile != null && request.mFilename != null) { uniFile.renameTo(request.mFilename); } // Listener if (listener != null) { listener.onSucceed(); } return true; } catch (Exception e) { // remove download failed file if (uniFile != null) { uniFile.delete(); } if (listener != null) { listener.onFailed(e); } return false; } finally { if (osPipe != null) { osPipe.close(); osPipe.release(); } } }
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 {// w ww. j a v a 2 s .co m // 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.kubeiwu.easyandroid.easyhttp.core.retrofit.Utils.java
License:Apache License
/** * Replace a {@link Response} with an identical copy whose body is backed by * a {@link Buffer} rather than a {@link Source}. *//*from w w w. ja va 2 s . com*/ public static ResponseBody readBodyToBytesIfNecessary(final ResponseBody body) throws IOException { if (body == null) { return null; } BufferedSource source = body.source(); Buffer buffer = new Buffer(); buffer.writeAll(source); source.close(); return ResponseBody.create(body.contentType(), body.contentLength(), buffer); }
From source file:com.pangbo.android.thirdframworks.retrofit.OkHttpCall.java
License:Apache License
private Response<T> 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(); 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. ResponseBody bufferedBody = Utils.readBodyToBytesIfNecessary(rawBody); return Response.error(bufferedBody, rawResponse); } finally { Utils.closeQuietly(rawBody); } } if (code == 204 || code == 205) { return Response.success(null, rawResponse); } ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody); try { T body = responseConverter.convert(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.pangbo.android.thirdframworks.retrofit.Utils.java
License:Apache License
/** * Replace a {@link Response} with an identical copy whose body is backed by a * {@link Buffer} rather than a .// ww w.ja v a2s . c om */ static ResponseBody readBodyToBytesIfNecessary(final ResponseBody body) throws IOException { if (body == null) { return null; } BufferedSource source = body.source(); Buffer buffer = new Buffer(); buffer.writeAll(source); source.close(); return ResponseBody.create(body.contentType(), body.contentLength(), buffer); }
From source file:com.phattn.vnexpressnews.io.OkHttpStack.java
License:Open Source License
private static HttpEntity entityFromOkHttpResponse(Response response) throws IOException { BasicHttpEntity entity = new BasicHttpEntity(); ResponseBody body = response.body(); entity.setContent(body.byteStream()); entity.setContentLength(body.contentLength()); entity.setContentEncoding(response.header("Content-Encoding")); if (body.contentType() != null) { entity.setContentType(body.contentType().type()); }/*from w ww .ja v a 2 s . co m*/ return entity; }
From source file:com.rafagarcia.countries.backend.webapi.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); }/* ww w.ja v a2s. 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() + ' ' + requestPath(request.httpUrl()) + ' ' + protocol(protocol); if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(requestStartMessage); if (logHeaders) { Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { logger.log(headers.name(i) + ": " + headers.value(i)); } if (logBody && hasRequestBody) { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { contentType.charset(UTF8); } logger.log(""); logger.log(buffer.readString(charset)); } String endMessage = "--> END " + request.method(); if (logBody && hasRequestBody) { endMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(endMessage); } long startNs = System.nanoTime(); Response response = chain.proceed(request); long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); logger.log("<-- " + protocol(response.protocol()) + ' ' + response.code() + ' ' + response.message() + " (" + tookMs + "ms" + (!logHeaders ? ", " + responseBody.contentLength() + "-byte 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) { Buffer buffer = new Buffer(); responseBody.source().readAll(buffer); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (responseBody.contentLength() > 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } // Since we consumed the original, replace the one-shot body in the response with a new one. response = response.newBuilder() .body(ResponseBody.create(contentType, responseBody.contentLength(), buffer)).build(); } String endMessage = "<-- END HTTP"; if (logBody) { endMessage += " (" + responseBody.contentLength() + "-byte body)"; } logger.log(endMessage); } return response; }
From source file:com.squareup.picasso252.OkHttpDownloader.java
License:Apache License
@Override public Response load(@NonNull Uri uri, int networkPolicy) throws IOException { CacheControl cacheControl = null;/*from w w w .j a v a 2s . c o m*/ if (networkPolicy != 0) { if (NetworkPolicy.isOfflineOnly(networkPolicy)) { cacheControl = CacheControl.FORCE_CACHE; } else { CacheControl.Builder builder = new CacheControl.Builder(); if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) { builder.noCache(); } if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) { builder.noStore(); } cacheControl = builder.build(); } } Request.Builder builder = new Request.Builder().url(uri.toString()); if (cacheControl != null) { builder.cacheControl(cacheControl); } com.squareup.okhttp.Response response = client.newCall(builder.build()).execute(); int responseCode = response.code(); if (responseCode >= 300) { response.body().close(); throw new ResponseException(responseCode + " " + response.message(), networkPolicy, responseCode); } boolean fromCache = response.cacheResponse() != null; ResponseBody responseBody = response.body(); return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength()); }
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 {//from w ww. j a v a 2 s.co m // 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); } }
From source file:com.xing.api.CallSpecTest.java
License:Apache License
private static void assertNoBodySuccessResponse(Response response, int code) throws IOException { assertThat(response.code()).isEqualTo(code); assertThat(response.error()).isNull(); assertThat(response.body()).isNull(); assertThat(response.isSuccess()).isTrue(); ResponseBody body = response.raw().body(); assertThat(body).isNotNull();//from w ww . ja va2 s .com // User may want to ignore the content of another response. if (code == 204 || code == 205) assertThat(body.contentLength()).isEqualTo(0L); assertThat(body.contentType()).isNull(); try { body.source(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Cannot read raw response body of a parsed body."); } }