Example usage for com.squareup.okhttp ResponseBody contentType

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

Introduction

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

Prototype

public abstract MediaType contentType();

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  w w.  j av  a  2 s  . c  om*/
        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.kubeiwu.easyandroid.easyhttp.core.retrofit.GsonConverter.java

License:Apache License

public T fromBody(ResponseBody value, Request request) throws IOException {
    String string = value.string();
    System.out.println(":" + string);
    Reader reader = new InputStreamReader((new ByteArrayInputStream(string.getBytes(UTF8))), Util.UTF_8);
    try {//w  w  w .j a  v  a2 s  .co m
        T t = typeAdapter.fromJson(reader);
        System.out.println("?" + t);
        String mimeType = value.contentType().toString();
        parseCache(request, t, string, mimeType);
        return t;
    } finally {
        closeQuietly(reader);
    }
}

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 www  . j av a  2 s .c  o  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 www  .  java2  s.co  m
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.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 w  ww.  j a va  2 s .com
    }

    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.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 {/*from   w w  w. 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 {
            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 ./*from w  ww .  j a  v a  2s .  com*/
 */
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.parse.ParseOkHttpClient.java

License:Open Source License

@Override
/* package */ ParseHttpResponse getResponse(Response okHttpResponse) throws IOException {
    // Status code
    int statusCode = okHttpResponse.code();

    // Content/*from  w  w  w. j ava2  s.c  o  m*/
    InputStream content = okHttpResponse.body().byteStream();

    // Total size
    int totalSize = (int) okHttpResponse.body().contentLength();

    // Reason phrase
    String reasonPhrase = okHttpResponse.message();

    // Headers
    Map<String, String> headers = new HashMap<>();
    for (String name : okHttpResponse.headers().names()) {
        headers.put(name, okHttpResponse.header(name));
    }

    // Content type
    String contentType = null;
    ResponseBody body = okHttpResponse.body();
    if (body != null && body.contentType() != null) {
        contentType = body.contentType().toString();
    }

    return new ParseHttpResponse.Builder().setStatusCode(statusCode).setContent(content).setTotalSize(totalSize)
            .setReasonPhrase(reasonPhrase).setHeaders(headers).setContentType(contentType).build();
}

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   ww w  .j  a  v a 2s .  c o 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. j a  va  2s.  com

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