Example usage for com.squareup.okhttp ResponseBody byteStream

List of usage examples for com.squareup.okhttp ResponseBody byteStream

Introduction

In this page you can find the example usage for com.squareup.okhttp ResponseBody byteStream.

Prototype

public final InputStream byteStream() throws IOException 

Source Link

Usage

From source file:com.granita.contacticloudsync.syncadapter.TasksSyncManager.java

License:Open Source License

@Override
protected void downloadRemote() throws IOException, HttpException, DavException, CalendarStorageException {
    log.info("Downloading " + toDownload.size() + " tasks (" + MAX_MULTIGET + " at once)");

    // download new/updated iCalendars from server
    for (DavResource[] bunch : ArrayUtils.partition(toDownload.toArray(new DavResource[toDownload.size()]),
            MAX_MULTIGET)) {// w ww .j  av  a2  s.co m
        if (Thread.interrupted())
            return;

        log.info("Downloading " + StringUtils.join(bunch, ", "));

        if (bunch.length == 1) {
            // only one contact, use GET
            DavResource remote = bunch[0];

            ResponseBody body = remote.get("text/calendar");
            String eTag = ((GetETag) remote.properties.get(GetETag.NAME)).eTag;

            Charset charset = Charsets.UTF_8;
            MediaType contentType = body.contentType();
            if (contentType != null)
                charset = contentType.charset(Charsets.UTF_8);

            @Cleanup
            InputStream stream = body.byteStream();
            processVTodo(remote.fileName(), eTag, stream, charset);

        } else {
            // multiple contacts, use multi-get
            List<HttpUrl> urls = new LinkedList<>();
            for (DavResource remote : bunch)
                urls.add(remote.location);
            davCalendar().multiget(urls.toArray(new HttpUrl[urls.size()]));

            // process multiget results
            for (DavResource remote : davCollection.members) {
                String eTag;
                GetETag getETag = (GetETag) remote.properties.get(GetETag.NAME);
                if (getETag != null)
                    eTag = getETag.eTag;
                else
                    throw new DavException("Received multi-get response without ETag");

                Charset charset = Charsets.UTF_8;
                GetContentType getContentType = (GetContentType) remote.properties.get(GetContentType.NAME);
                if (getContentType != null && getContentType.type != null) {
                    MediaType type = MediaType.parse(getContentType.type);
                    if (type != null)
                        charset = type.charset(Charsets.UTF_8);
                }

                CalendarData calendarData = (CalendarData) remote.properties.get(CalendarData.NAME);
                if (calendarData == null || calendarData.iCalendar == null)
                    throw new DavException("Received multi-get response without address data");

                @Cleanup
                InputStream stream = new ByteArrayInputStream(calendarData.iCalendar.getBytes());
                processVTodo(remote.fileName(), eTag, stream, charset);
            }
        }
    }
}

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  w  w 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.jaspersoft.android.jaspermobile.webview.intercept.okhttp.OkResponseMapper.java

License:Open Source License

private InputStream extractData(Response response) {
    ResponseBody body = response.body();
    if (body == null) {
        return null;
    }/*from   w ww . j  a  va 2 s . c  o m*/
    try {
        return body.byteStream();
    } catch (IOException e) {
        return null;
    }
}

From source file:com.microsoft.rest.ServiceResponseBuilder.java

License:Open Source License

/**
 * Builds the body object from the HTTP status code and returned response
 * body undeserialized and wrapped in {@link ResponseBody}.
 *
 * @param statusCode the HTTP status code
 * @param responseBody the response body
 * @return the response body, deserialized
 * @throws IOException thrown for any deserialization errors
 *///from   www.ja v  a2s  .com
protected Object buildBody(int statusCode, ResponseBody responseBody) throws IOException {
    if (responseBody == null) {
        return null;
    }

    Type type;
    if (responseTypes.containsKey(statusCode)) {
        type = responseTypes.get(statusCode);
    } else if (responseTypes.get(0) != Object.class) {
        type = responseTypes.get(0);
    } else {
        type = new TypeReference<T>() {
        }.getType();
    }

    // Void response
    if (type == Void.class) {
        return null;
    }
    // Return raw response if InputStream is the target type
    else if (type == InputStream.class) {
        return responseBody.byteStream();
    }
    // Deserialize
    else {
        String responseContent = responseBody.string();
        if (responseContent.length() <= 0) {
            return null;
        }
        return mapperAdapter.deserialize(responseContent, type);
    }
}

From source file:com.mobimvp.cliques.util.StethoInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    String requestId = String.valueOf(mNextRequestId.getAndIncrement());
    Request request = chain.request();
    int requestSize = 0;
    if (mEventReporter.isEnabled()) {
        OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request);
        mEventReporter.requestWillBeSent(inspectorRequest);
        byte[] requestBody = inspectorRequest.body();
        if (requestBody != null) {
            requestSize += requestBody.length;
        }/*from ww  w  . j  a  v  a  2  s. co  m*/
    }

    Response response;
    try {
        response = chain.proceed(request);
    } catch (IOException e) {
        if (mEventReporter.isEnabled()) {
            mEventReporter.httpExchangeFailed(requestId, e.toString());
        }
        throw e;
    }

    if (mEventReporter.isEnabled()) {
        if (requestSize > 0) {
            mEventReporter.dataSent(requestId, requestSize, requestSize);
        }

        Connection connection = chain.connection();
        mEventReporter
                .responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection));

        ResponseBody body = response.body();
        MediaType contentType = null;
        InputStream responseStream = null;
        if (body != null) {
            contentType = body.contentType();
            responseStream = body.byteStream();
        }

        responseStream = mEventReporter.interpretResponseStream(requestId,
                contentType != null ? contentType.toString() : null, response.header("Content-Encoding"),
                responseStream, new DefaultResponseHandler(mEventReporter, requestId));
        if (responseStream != null) {
            response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build();
        }
    }

    return response;
}

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  w  w  .j av a  2 s  .c  o  m*/
    return entity;
}

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 .jav  a2s.co 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.taobao.weex.devtools.inspector.network.OkHttpInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    String requestId = String.valueOf(mNextRequestId.getAndIncrement());

    Request request = chain.request();

    RequestBodyHelper requestBodyHelper = null;
    if (mEventReporter.isEnabled()) {
        requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId);
        OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request,
                requestBodyHelper);// ww  w  .j a va  2 s.  c o  m
        mEventReporter.requestWillBeSent(inspectorRequest);
    }

    Response response;
    try {
        response = chain.proceed(request);
    } catch (IOException e) {
        if (mEventReporter.isEnabled()) {
            mEventReporter.httpExchangeFailed(requestId, e.toString());
        }
        throw e;
    }

    if (mEventReporter.isEnabled()) {
        if (requestBodyHelper != null && requestBodyHelper.hasBody()) {
            requestBodyHelper.reportDataSent();
        }

        Connection connection = chain.connection();
        mEventReporter
                .responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection));

        ResponseBody body = response.body();
        MediaType contentType = null;
        InputStream responseStream = null;
        if (body != null) {
            contentType = body.contentType();
            responseStream = body.byteStream();
        }

        responseStream = mEventReporter.interpretResponseStream(requestId,
                contentType != null ? contentType.toString() : null, response.header("Content-Encoding"),
                responseStream, new DefaultResponseHandler(mEventReporter, requestId));
        if (responseStream != null) {
            response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build();
        }
    }

    return response;
}

From source file:com.yandex.disk.rest.LoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    String hash = Integer.toHexString(chain.hashCode());
    String sendPrefix = hash + SEND_PREFIX;
    String receivePrefix = hash + RECEIVE_PREFIX;

    if (logWire) {
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            logger.info(sendPrefix + "request: " + requestBody);
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            byte[] requestBuffer = ByteStreams.toByteArray(buffer.inputStream());
            logBuffer(sendPrefix, requestBuffer);
        }/*www. j  av  a 2 s  .co m*/
        request = request.newBuilder().removeHeader("Accept-Encoding").addHeader("Accept-Encoding", "").build();
    }

    logger.info(sendPrefix + request.method() + " " + request.url());
    logger.info(sendPrefix + "on " + chain.connection());
    logHeaders(sendPrefix, request.headers());

    Response response = chain.proceed(request);
    logger.info(receivePrefix + response.protocol() + " " + response.code() + " " + response.message());
    logHeaders(receivePrefix, response.headers());

    if (logWire) {
        ResponseBody body = response.body();
        byte[] responseBuffer = ByteStreams.toByteArray(body.byteStream());
        response = response.newBuilder().body(ResponseBody.create(body.contentType(), responseBuffer)).build();
        logBuffer(receivePrefix, responseBuffer);
    }

    return response;
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

void downloadUrl(final String url, final DownloadListener downloadListener)
        throws IOException, CancelledDownloadException, DownloadNoSpaceAvailableException, HttpCodeException {

    Request.Builder req = buildRequest().url(url);

    long length = downloadListener.getLocalLength();
    String ifTag = "If-None-Match";
    if (length >= 0) {
        ifTag = "If-Range";
        StringBuilder contentRange = new StringBuilder();
        contentRange.append("bytes=").append(length).append("-");
        logger.debug("Range: " + contentRange);
        req.addHeader("Range", contentRange.toString());
    }//from w  w  w  . ja  v  a2s . com

    String etag = downloadListener.getETag();
    if (etag != null) {
        logger.debug(ifTag + ": " + etag);
        req.addHeader(ifTag, etag);
    }

    Request request = req.build();
    Response response = client.newCall(request).execute();

    boolean partialContent = false;
    int code = response.code();
    switch (code) {
    case 200:
        // OK
        break;
    case 206:
        partialContent = true;
        break;
    case 304:
        throw new FileNotModifiedException(code);
    case 404:
        throw new NotFoundException(code);
    case 416:
        throw new RangeNotSatisfiableException(code);
    default:
        throw new HttpCodeException(code);
    }

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    logger.debug("download: contentLength=" + contentLength);

    long loaded;
    if (partialContent) {
        ContentRangeResponse contentRangeResponse = parseContentRangeHeader(response.header("Content-Range"));
        logger.debug("download: contentRangeResponse=" + contentRangeResponse);
        if (contentRangeResponse != null) {
            loaded = contentRangeResponse.getStart();
            contentLength = contentRangeResponse.getSize();
        } else {
            loaded = length;
        }
    } else {
        loaded = 0;
        if (contentLength < 0) {
            contentLength = 0;
        }
    }

    OutputStream os = null;
    try {
        downloadListener.setStartPosition(loaded);
        MediaType contentTypeHeader = responseBody.contentType();
        if (contentTypeHeader != null) {
            downloadListener.setContentType(contentTypeHeader.toString());
        }
        downloadListener.setContentLength(contentLength);

        int count;
        InputStream content = responseBody.byteStream();
        os = downloadListener.getOutputStream(partialContent);
        final byte[] downloadBuffer = new byte[1024];
        while ((count = content.read(downloadBuffer)) != -1) {
            if (downloadListener.hasCancelled()) {
                logger.info("Downloading " + url + " canceled");
                client.cancel(request.tag());
                throw new CancelledDownloadException();
            }
            os.write(downloadBuffer, 0, count);
            loaded += count;
            downloadListener.updateProgress(loaded, contentLength);
        }
    } catch (CancelledDownloadException ex) {
        throw ex;
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        client.cancel(request.tag());
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else if (e instanceof DownloadNoSpaceAvailableException) {
            throw (DownloadNoSpaceAvailableException) e;
        } else {
            // never happen
            throw new RuntimeException(e);
        }
    } finally {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException ex) {
            // nothing
        }
        try {
            response.body().close();
        } catch (IOException | NullPointerException ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }
}