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.aix.city.comm.OkHttpStack.java

License:Open Source License

private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();
    ResponseBody body = r.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(r.header("Content-Encoding"));

    if (body.contentType() != null) {
        entity.setContentType(body.contentType().type());
    }/*from   w  w  w  .  j  a  va2 s .c  om*/
    return entity;
}

From source file:com.androidso.lib.net.http.OkHttpStack.java

License:Open Source License

private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity() {
        @Override/*from   w  w w  .  j  a v  a2 s .  c o m*/
        public void consumeContent() {
            //                getContent().close();

        }
    };
    ResponseBody body = r.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(r.header("Content-Encoding"));

    if (body.contentType() != null) {
        entity.setContentType(body.contentType().type());
    }
    return entity;
}

From source file:com.example.admin.angpangii.ext.OkHttpImageDownloader.java

License:Apache License

@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
    Request request = new Request.Builder().url(imageUri).build();
    ResponseBody responseBody = client.newCall(request).execute().body();
    InputStream inputStream = responseBody.byteStream();
    int contentLength = (int) responseBody.contentLength();
    return new ContentLengthInputStream(inputStream, contentLength);
}

From source file:com.example.ivy.picassodemo.MyOkHttpDownloader.java

License:Apache License

@Override
public Response load(Uri uri, int networkPolicy) throws IOException {
    CacheControl cacheControl = null;//from w  ww .  j a  v  a  2 s.  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.facebook.imagepipeline.backends.okhttp.OkHttpNetworkFetcher.java

License:Open Source License

@Override
public void fetch(final OkHttpNetworkFetchState fetchState, final Callback callback) {
    fetchState.submitTime = SystemClock.elapsedRealtime();
    final Uri uri = fetchState.getUri();
    final Request request = new Request.Builder().cacheControl(new CacheControl.Builder().noStore().build())
            .url(uri.toString()).get().build();
    final Call call = mOkHttpClient.newCall(request);

    fetchState.getContext().addCallbacks(new BaseProducerContextCallbacks() {
        @Override/*w  ww .  j a  v  a 2  s . c  o m*/
        public void onCancellationRequested() {
            if (Looper.myLooper() != Looper.getMainLooper()) {
                call.cancel();
            } else {
                mCancellationExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        call.cancel();
                    }
                });
            }
        }
    });

    call.enqueue(new com.squareup.okhttp.Callback() {
        @Override
        public void onResponse(Response response) {
            fetchState.responseTime = SystemClock.elapsedRealtime();
            final ResponseBody body = response.body();
            try {
                long contentLength = body.contentLength();
                if (contentLength < 0) {
                    contentLength = 0;
                }
                callback.onResponse(body.byteStream(), (int) contentLength);
            } catch (Exception e) {
                handleException(call, e, callback);
            } finally {
                try {
                    body.close();
                } catch (Exception e) {
                    FLog.w(TAG, "Exception when closing response body", e);
                }
            }
        }

        @Override
        public void onFailure(final Request request, final IOException e) {
            handleException(call, e, callback);
        }
    });
}

From source file:com.facebook.imagepipeline.backends.okhttp.OkHttpNetworkFetchProducer.java

License:Open Source License

@Override
protected void fetchImage(final NfpRequestState requestState) {
    final Uri uri = requestState.getUri();
    final Request request = new Request.Builder().cacheControl(new CacheControl.Builder().noStore().build())
            .url(uri.toString()).get().build();
    final Call call = mOkHttpClient.newCall(request);

    if (mCancellable) {
        requestState.getContext().addCallbacks(new BaseProducerContextCallbacks() {
            @Override/*  www . ja  v  a 2 s.c o  m*/
            public void onCancellationRequested() {
                call.cancel();
            }
        });
    }

    call.enqueue(new Callback() {
        @Override
        public void onResponse(Response response) {
            final ResponseBody body = response.body();
            try {
                long contentLength = body.contentLength();
                if (contentLength < 0) {
                    contentLength = 0;
                }
                processResult(requestState, body.byteStream(), (int) contentLength, false);
            } catch (IOException ioe) {
                handleException(call, requestState, ioe);
            } finally {
                try {
                    body.close();
                } catch (IOException ioe) {
                    FLog.w(TAG, "Exception when closing response body", ioe);
                }
            }
        }

        @Override
        public void onFailure(final Request request, final IOException e) {
            handleException(call, requestState, e);
        }
    });
}

From source file:com.facebook.stetho.okhttp.StethoInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    String requestId = mEventReporter.nextRequestId();

    Request request = chain.request();

    RequestBodyHelper requestBodyHelper = null;
    if (mEventReporter.isEnabled()) {
        requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId);
        OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request,
                requestBodyHelper);/*from w  ww . java 2s.co  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.github.mmatczuk.ablb.benchmark.OkHttpAsync.java

License:Apache License

@Override
public void prepare(final Benchmark benchmark) {
    concurrencyLevel = benchmark.concurrencyLevel;
    targetBacklog = benchmark.targetBacklog;

    client = new OkHttpClient();
    client.setDispatcher(new Dispatcher(new ThreadPoolExecutor(benchmark.concurrencyLevel,
            benchmark.concurrencyLevel, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>())));

    callback = new Callback() {
        @Override//from  w w  w .j  ava2  s .  c  o  m
        public void onFailure(Request request, IOException e) {
            System.out.println("Failed: " + e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            ResponseBody body = response.body();
            long total = readAllAndClose(body.byteStream());
            long finish = System.nanoTime();
            if (VERBOSE) {
                long start = (Long) response.request().tag();
                System.out.printf("Transferred % 8d bytes in %4d ms%n", total,
                        TimeUnit.NANOSECONDS.toMillis(finish - start));
            }
            requestsInFlight.decrementAndGet();
        }
    };
}

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

License:Open Source License

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

    // download new/updated iCalendars from server
    for (DavResource[] bunch : ArrayUtils.partition(toDownload.toArray(new DavResource[toDownload.size()]),
            MAX_MULTIGET)) {//  w w w.ja  va  2  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();
            processVEvent(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());
                processVEvent(remote.fileName(), eTag, stream, charset);
            }
        }
    }
}

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

License:Open Source License

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

    // prepare downloader which may be used to download external resource like contact photos
    Contact.Downloader downloader = new ResourceDownloader(httpClient, collectionURL);

    // download new/updated VCards from server
    for (DavResource[] bunch : ArrayUtils.partition(toDownload.toArray(new DavResource[toDownload.size()]),
            MAX_MULTIGET)) {/*from  www  .  ja  va 2s .  c o  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/vcard;version=4.0, text/vcard;charset=utf-8;q=0.8, text/vcard;q=0.5");
            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();
            processVCard(remote.fileName(), eTag, stream, charset, downloader);

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

            // 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);
                }

                AddressData addressData = (AddressData) remote.properties.get(AddressData.NAME);
                if (addressData == null || addressData.vCard == null)
                    throw new DavException("Received multi-get response without address data");

                @Cleanup
                InputStream stream = new ByteArrayInputStream(addressData.vCard.getBytes());
                processVCard(remote.fileName(), eTag, stream, charset, downloader);
            }
        }
    }
}