Example usage for com.squareup.okhttp Response body

List of usage examples for com.squareup.okhttp Response body

Introduction

In this page you can find the example usage for com.squareup.okhttp Response body.

Prototype

ResponseBody body

To view the source code for com.squareup.okhttp Response body.

Click Source Link

Usage

From source file:com.battlelancer.seriesguide.thetvdbapi.TheTVDB.java

License:Apache License

/**
 * Downloads the XML or ZIP file from the given URL, passing a valid response to {@link
 * Xml#parse(InputStream, android.util.Xml.Encoding, ContentHandler)} using the given {@link
 * ContentHandler}./*from   w ww  .  j a  v a2s . c o m*/
 */
private static void downloadAndParse(Context context, ContentHandler handler, String urlString,
        boolean isZipFile) throws TvdbException {
    Request request = new Request.Builder().url(urlString).build();

    Response response;
    try {
        response = ServiceUtils.getCachingOkHttpClient(context).newCall(request).execute();
    } catch (IOException e) {
        throw new TvdbException(e.getMessage() + " " + urlString, e);
    }

    int statusCode = response.code();
    if (statusCode == 404) {
        // special case: item does not exist (any longer)
        throw new TvdbException(response.code() + " " + response.message() + " " + urlString, true, null);
    }
    if (!response.isSuccessful()) {
        // other non-2xx response
        throw new TvdbException(response.code() + " " + response.message() + " " + urlString);
    }

    try {
        final InputStream input = response.body().byteStream();
        if (isZipFile) {
            // We downloaded the compressed file from TheTVDB
            final ZipInputStream zipin = new ZipInputStream(input);
            zipin.getNextEntry();
            try {
                Xml.parse(zipin, Xml.Encoding.UTF_8, handler);
            } finally {
                zipin.close();
            }
        } else {
            try {
                Xml.parse(input, Xml.Encoding.UTF_8, handler);
            } finally {
                if (input != null) {
                    input.close();
                }
            }
        }
    } catch (SAXException | IOException | AssertionError e) {
        throw new TvdbException(e.getMessage() + " " + urlString, e);
    }
}

From source file:com.braisgabin.fbstats.Api.java

License:Apache License

public <T> T download(String url, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
    Request request = new Request.Builder().url(url).addHeader("Authorization", "OAuth " + accessToken).build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        throw new RuntimeException(response.body().string());
    }//from w  ww  .j  a  v a2s .  co  m
    return mapper.readValue(response.body().byteStream(), clazz);
}

From source file:com.brq.wallet.bitid.BitIdAuthenticator.java

License:Microsoft Reference Source License

public BitIdResponse queryServer() {
    final BitIdResponse bitIdResponse = new BitIdResponse();
    final SignedMessage signature = privateKey.signMessage(request.getFullUri());
    try {/* w ww . j a va  2 s .  c  o m*/
        OkHttpClient client = getOkHttpClient();
        Request request = getRequest(signature);
        Response callResponse = client.newCall(request).execute();

        bitIdResponse.code = callResponse.code();

        if (bitIdResponse.code >= 200 && bitIdResponse.code < 300) {
            bitIdResponse.status = BitIdResponse.ResponseStatus.SUCCESS;
            bitIdResponse.message = callResponse.body().string();
        } else {
            bitIdResponse.status = BitIdResponse.ResponseStatus.ERROR;
            bitIdResponse.message = formatErrorMessage(callResponse.body().string());

        }

    } catch (SocketTimeoutException e) {
        //connection timed out
        bitIdResponse.status = BitIdResponse.ResponseStatus.TIMEOUT;
    } catch (InterruptedIOException e) {
        //seems like this can also happen when a timeout occurs
        bitIdResponse.status = BitIdResponse.ResponseStatus.TIMEOUT;
    } catch (UnknownHostException e) {
        //host not known, most probably the device has no internet connection
        bitIdResponse.status = BitIdResponse.ResponseStatus.NOCONNECTION;
    } catch (ConnectException e) {
        //might be a refused connection
        bitIdResponse.status = BitIdResponse.ResponseStatus.REFUSED;
    } catch (SSLException e) {
        Preconditions.checkState(enforceSslCorrectness);
        //ask user whether he wants to proceed although there is a problem with the certificate
        bitIdResponse.message = e.getLocalizedMessage();
        bitIdResponse.status = BitIdResponse.ResponseStatus.SSLPROBLEM;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return bitIdResponse;
}

From source file:com.camel.crawler.WebCrawler.java

License:Open Source License

public void fetchWeb(String url) throws IOException {
    client.setConnectTimeout(2, TimeUnit.SECONDS);
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();

    int responseCode = response.code();

    if (responseCode == 200) {
        extraInfo(response.body().string());
    } else {/*from  w w w  . j a  va  2  s  .  c  o  m*/
        System.out.println("got error page");
    }
}

From source file:com.capstone.transit.trans_it.TripPlannerActivity.java

License:Open Source License

private void getDirections(LatLng origin, LatLng destination) {

    final String directionsURL = getDirectionsUrl(origin, destination);
    Log.v(TAG, directionsURL);/* w  ww .j a  v  a  2  s . c  om*/

    if (isNetworkAvailable()) {

        Thread T = new Thread() {
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(directionsURL).build();

                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    String jsonData = response.body().string();

                    Log.v(TAG, jsonData);

                    if (response.isSuccessful()) {

                        mStep = getSteps(jsonData);

                    } else {
                        alertUserAboutError();
                    }
                } catch (JSONException | IOException e) {
                    e.printStackTrace();
                }

            }
        };
        T.start();

        try {
            T.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    } else {
        Toast.makeText(this, "unavailable network", Toast.LENGTH_LONG).show();
    }
}

From source file:com.carlospinan.demoretrofit2.helpers.LoggingInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    Log.d(LOG_TAG, String.format("--> Sending request %s on %s%n%s", request.url(), chain.connection(),
            request.headers()));/*from w w  w.j  ava 2  s.com*/

    Buffer requestBuffer = new Buffer();
    if (request.body() != null) {
        request.body().writeTo(requestBuffer);
        Log.d(LOG_TAG, requestBuffer.readUtf8());
    }

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    Log.d(LOG_TAG, String.format("<-- Received response for %s in %.1fms%n%s", response.request().url(),
            (t2 - t1) / 1e6d, response.headers()));

    MediaType contentType = response.body().contentType();
    String content = response.body().string();
    Log.d(LOG_TAG, content);

    ResponseBody wrappedBody = ResponseBody.create(contentType, content);
    return response.newBuilder().body(wrappedBody).build();
}

From source file:com.cdancy.artifactory.rest.config.ArtifactoryOkHttpCommandExecutorService.java

License:Apache License

@Override
protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException {

    OkHttpClient requestScopedClient = clientSupplier.get();
    requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri()));
    Response response = requestScopedClient.newCall(nativeRequest).execute();

    HttpResponse.Builder<?> builder = HttpResponse.builder();
    builder.statusCode(response.code());
    builder.message(response.message());

    Builder<String, String> headerBuilder = ImmutableMultimap.builder();
    Headers responseHeaders = response.headers();

    // Check for Artifactory header and init potential file for downstream use
    File destinationFile = null;//from   ww  w  . j a  va 2  s  . c om
    String artFileName = responseHeaders.get("X-Artifactory-Filename");
    if (artFileName != null) {

        GAVCoordinates gavCoordinates = ArtifactoryUtils.gavFromURL(nativeRequest.url(),
                endpoint.get().toURL());
        destinationFile = ArtifactoryUtils.getGradleFile(gavCoordinates, artFileName,
                responseHeaders.get("ETag"));
        headerBuilder.put(ArtifactoryUtils.LOCATION_HEADER, destinationFile.getAbsolutePath());
    }

    for (String header : responseHeaders.names()) {
        headerBuilder.putAll(header, responseHeaders.values(header));
    }

    ImmutableMultimap<String, String> headers = headerBuilder.build();

    if (response.code() == 204 && response.body() != null) {
        response.body().close();
    } else {
        if (destinationFile != null) {
            if (!destinationFile.exists() || (destinationFile.length() != response.body().contentLength())) {
                InputStream inputStream = null;
                try {
                    inputStream = response.body().byteStream();
                    ArtifactoryUtils.resolveInputStream(inputStream, destinationFile);
                } catch (Exception e) {
                    Throwables.propagate(e);
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            }
            IOUtils.closeQuietly(response.body().byteStream());
        } else {
            Payload payload = newInputStreamPayload(response.body().byteStream());
            contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);
            builder.payload(payload);
        }
    }

    builder.headers(filterOutContentHeaders(headers));
    return builder.build();
}

From source file:com.chromium.fontinstaller.core.FontDownloader.java

License:Apache License

private static Observable<File> downloadFile(final String url, final String path) {
    return Observable.create(subscriber -> {
        final Request request = new Request.Builder().url(url).build();
        try {//from w ww.  java2  s .  c  o  m
            if (!subscriber.isUnsubscribed()) {
                final File file = new File(path);
                if (!file.exists()) {
                    final Response response = CLIENT.newCall(request).execute();
                    final BufferedSink sink = Okio.buffer(Okio.sink(file));
                    sink.writeAll(response.body().source());
                    sink.close();
                }
                subscriber.onNext(file);
                subscriber.onCompleted();
            }
        } catch (IOException e) {
            subscriber.onError(new DownloadException(e));
        }
    });
}

From source file:com.cinchapi.concourse.http.HttpTest.java

License:Apache License

/**
 * Return a JsonElement representation of the response body.
 * //from w  w w.j  a va 2  s .co  m
 * @param response
 * @param the json response
 */
protected static JsonElement bodyAsJson(Response response) {
    try {
        String body = response.body().string();
        JsonElement json = new JsonParser().parse(body);
        Variables.register("json_body_" + response.hashCode(), body);
        return json;
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.cml.rx.android.api.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);
    }//from  w  ww . j av  a2s  .  c om

    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() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

    if (logHeaders) {
        if (hasRequestBody) {
            // Request body headers are only present when installed as a
            // network interceptor. Force
            // them to be included (when available) so there values are
            // known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }

        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly
            // logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }

        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            logger.log("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength()
                        + "-byte body omitted)");
            }
        }
    }

    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " ("
            + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " 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 || !HttpEngine.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    logger.log("");
                    logger.log("Couldn't decode the response body; charset is likely malformed.");
                    logger.log("<-- END HTTP");

                    return response;
                }
            }

            if (!isPlaintext(buffer)) {
                logger.log("");
                logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }

            if (contentLength != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }

            logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
    }

    return response;
}