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:org.kegbot.api.KegbotApiImpl.java

License:Open Source License

private JsonNode requestJson(Request request) throws KegbotApiException {
    final Response response;
    final long startTime = SystemClock.elapsedRealtime();
    try {//from   w  w  w . j  a  v  a 2  s.c om
        response = mClient.newCall(request).execute();
    } catch (IOException e) {
        Log.w(TAG, String.format("--> %s %s [ERR]", request.method(), request.urlString()));
        throw new KegbotApiException(e);
    }
    final long endTime = SystemClock.elapsedRealtime();

    final int responseCode = response.code();
    final String logMessage = String.format("--> %s %s [%s] %sms", request.method(), request.urlString(),
            responseCode, endTime - startTime);
    if (responseCode >= 200 && responseCode < 300) {
        Log.d(TAG, logMessage);
    } else {
        Log.w(TAG, logMessage);
    }
    final ResponseBody body = response.body();

    final JsonNode rootNode;
    try {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            rootNode = mapper.readValue(body.byteStream(), JsonNode.class);
        } finally {
            body.close();
        }
    } catch (JsonParseException e) {
        throw new KegbotApiMalformedResponseException(e);
    } catch (JsonMappingException e) {
        throw new KegbotApiMalformedResponseException(e);
    } catch (IOException e) {
        throw new KegbotApiException(e);
    }

    boolean success = false;
    try {
        // Handle structural errors.
        if (!rootNode.has("meta")) {
            throw new KegbotApiMalformedResponseException("Response is missing 'meta' field.");
        }
        final JsonNode meta = rootNode.get("meta");
        if (!meta.isContainerNode()) {
            throw new KegbotApiMalformedResponseException("'meta' field is wrong type.");
        }

        final String message;
        if (rootNode.has("error") && rootNode.get("error").has("message")) {
            message = rootNode.get("error").get("message").getTextValue();
        } else {
            message = null;
        }

        // Handle HTTP errors.
        if (responseCode < 200 || responseCode >= 400) {
            switch (responseCode) {
            case 401:
                throw new NotAuthorizedException(message);
            case 404:
                throw new KegbotApi404(message);
            case 405:
                throw new MethodNotAllowedException(message);
            default:
                if (message != null) {
                    throw new KegbotApiServerError(message);
                } else {
                    throw new KegbotApiServerError("Server error, response code=" + responseCode);
                }
            }
        }

        success = true;
        return rootNode;
    } finally {
        if (!success) {
            Log.d(TAG, "Response JSON was: " + rootNode.toString());
        }
    }
}

From source file:org.quantumbadger.redreader.http.okhttp.OKHTTPBackend.java

License:Open Source License

@Override
public Request prepareRequest(final Context context, final RequestDetails details) {

    final com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder();

    builder.header("User-Agent", Constants.ua(context));

    final List<PostField> postFields = details.getPostFields();

    if (postFields != null) {
        builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
                PostField.encodeList(postFields)));

    } else {// w w  w  . j a  v a 2  s.  co m
        builder.get();
    }

    builder.url(details.getUrl().toString());
    builder.cacheControl(CacheControl.FORCE_NETWORK);

    final AtomicReference<Call> callRef = new AtomicReference<>();

    return new Request() {

        public void executeInThisThread(final Listener listener) {

            final Call call = mClient.newCall(builder.build());
            callRef.set(call);

            try {

                final Response response;

                try {
                    response = call.execute();
                } catch (IOException e) {
                    listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, e, null);
                    return;
                }

                final int status = response.code();

                if (status == 200 || status == 202) {

                    final ResponseBody body = response.body();
                    final InputStream bodyStream;
                    final Long bodyBytes;

                    if (body != null) {
                        bodyStream = body.byteStream();
                        bodyBytes = body.contentLength();

                    } else {
                        // TODO error
                        bodyStream = null;
                        bodyBytes = null;
                    }

                    final String contentType = response.header("Content-Type");

                    listener.onSuccess(contentType, bodyBytes, bodyStream);

                } else {
                    listener.onError(CacheRequest.REQUEST_FAILURE_REQUEST, null, status);
                }

            } catch (Throwable t) {
                listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, t, null);
            }
        }

        @Override
        public void cancel() {
            final Call call = callRef.getAndSet(null);
            if (call != null) {
                call.cancel();
            }
        }

        @Override
        public void addHeader(final String name, final String value) {
            builder.addHeader(name, value);
        }
    };
}

From source file:org.sonar.runner.impl.ServerConnection.java

License:Open Source License

/**
 * Download file, without any caching mechanism.
 *
 * @param urlPath path starting with slash, for instance {@code "/batch/index"}
 * @param toFile  the target file/*from   w ww  .  j  a  v  a 2s. co m*/
 * @throws IOException           if connectivity problem or timeout (network) or IO error (when writing to file)
 * @throws IllegalStateException if HTTP response code is different than 2xx
 */
public void downloadFile(String urlPath, File toFile) throws IOException {
    if (!urlPath.startsWith("/")) {
        throw new IllegalArgumentException(format("URL path must start with slash: %s", urlPath));
    }
    String url = baseUrlWithoutTrailingSlash + urlPath;
    logger.debug(format("Download %s to %s", url, toFile.getAbsolutePath()));
    ResponseBody responseBody = callUrl(url);

    try (OutputStream fileOutput = new FileOutputStream(toFile)) {
        IOUtils.copyLarge(responseBody.byteStream(), fileOutput);
    } catch (IOException | RuntimeException e) {
        FileUtils.deleteQuietly(toFile);
        throw e;
    }
}

From source file:retrofit.converter.GsonConverter.java

License:Apache License

@Override
public Object fromBody(ResponseBody body, Type type) throws IOException {
    Charset charset = this.charset;
    if (body.contentType() != null) {
        charset = body.contentType().charset(charset);
    }/*w w  w.  ja v  a 2 s.c o  m*/

    InputStream is = body.byteStream();
    try {
        return gson.fromJson(new InputStreamReader(is, charset), type);
    } finally {
        try {
            is.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:retrofit.JacksonConverter.java

License:Apache License

@Override
public T fromBody(ResponseBody body) throws IOException {
    InputStream is = body.byteStream();
    try {/*from w w  w  .  j a va 2 s.  co m*/
        return reader.readValue(is);
    } finally {
        try {
            is.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:retrofit.ProtoConverter.java

License:Apache License

@Override
public T fromBody(ResponseBody body) throws IOException {
    InputStream is = body.byteStream();
    try {//from   ww w.  ja v a  2  s. c o  m
        return parser.parseFrom(is);
    } catch (InvalidProtocolBufferException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            is.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:retrofit.ProtoResponseBodyConverter.java

License:Apache License

@Override
public T convert(ResponseBody value) throws IOException {
    InputStream is = value.byteStream();
    try {//w  w  w .  ja  v a 2  s .c om
        return parser.parseFrom(is);
    } catch (InvalidProtocolBufferException e) {
        throw new RuntimeException(e); // Despite extending IOException, this is data mismatch.
    } finally {
        Utils.closeQuietly(is);
    }
}

From source file:retrofit.SimpleXmlConverter.java

License:Apache License

@Override
public T fromBody(ResponseBody body) throws IOException {
    InputStream is = body.byteStream();
    try {/*  w ww  .  j a  v a 2  s .co m*/
        T read = serializer.read(cls, is, strict);
        if (read == null) {
            throw new IllegalStateException("Could not deserialize body as " + cls);
        }
        return read;
    } catch (RuntimeException | IOException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            is.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:retrofit.SimpleXmlResponseBodyConverter.java

License:Apache License

@Override
public T convert(ResponseBody value) throws IOException {
    InputStream is = value.byteStream();
    try {/*  w  w w . ja va2 s.  c o  m*/
        T read = serializer.read(cls, is, strict);
        if (read == null) {
            throw new IllegalStateException("Could not deserialize body as " + cls);
        }
        return read;
    } catch (RuntimeException | IOException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            is.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:retrofit.WireConverter.java

License:Apache License

@Override
public T fromBody(ResponseBody body) throws IOException {
    InputStream in = body.byteStream();
    try {//from w ww.j  av a 2 s  .co  m
        return wire.parseFrom(in, cls);
    } finally {
        try {
            in.close();
        } catch (IOException ignored) {
        }
    }
}