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.hkm.root.Tasks.upload_data.java

License:Open Source License

public void execute_upload(Request requestBuild) throws IOException, Exception {
    // executes generic request
    OkHttpClient use_client = client.clone();
    use_client.setWriteTimeout(10, TimeUnit.SECONDS);
    Response response = use_client.newCall(requestBuild).execute();
    if (!response.isSuccessful()) {
        throw new IOException("Unexpected code " + response);
    } else {/*  w  ww.  j ava 2 s.c o  m*/
        if (!response.body().string().isEmpty()) {
            success_events_achieved++;
            // sb.append(response.body().string());
            System.out.println(response.body().string());
            // StandJsonResponse sp = new StandJsonResponse();
            // sp.fromString(response.body().string()).setSingleSuccessAction(success_pass_event).run();
        } else {
            throw new Exception("response body is empty");
        }
    }
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.analytics.internal.NetworkLoggingInterceptor.java

License:Apache License

protected JSONObject generateRoundTripRequestAnalyticsMetadata(Request request, long startTime,
        String trackingID, Response response) throws IOException {
    JSONObject metadata = new JSONObject();

    long endTime = System.currentTimeMillis();

    try {//from   w w  w  .  ja  v  a2 s .  c o m
        metadata.put("$path", request.urlString());
        metadata.put(BMSAnalytics.CATEGORY, "network");
        metadata.put("$trackingid", trackingID);
        metadata.put("$outboundTimestamp", startTime);
        metadata.put("$inboundTimestamp", endTime);
        metadata.put("$roundTripTime", endTime - startTime);

        if (response != null) {
            metadata.put("$responseCode", response.code());
        }

        if (response != null && response.body() != null && response.body().contentLength() >= 0) {
            metadata.put("$bytesReceived", response.body().contentLength());
        }

        return metadata;
    } catch (JSONException e) {
        //Do nothing, since it is just for analytics.
        return null;
    }
}

From source file:com.ibm.watson.developer_cloud.service.WatsonService.java

License:Open Source License

/**
 * Execute the HTTP request and discard the response. Use this when you don't want to get the
 * response but you want to make sure we read it so that the underline connection is released
 * // w  ww.java  2s . c  o  m
 * @param request the request
 */
protected void executeWithoutResponse(Request request) {
    final Response response = execute(request);

    // close the response
    try {
        response.body().close();
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ibm.watson.developer_cloud.util.ResponseUtil.java

License:Open Source License

/**
 * Returns the HTTP Response {@link InputStream}.
 * //from  ww w.  j a  v a 2 s.  co  m
 * @param response an HTTP response
 * @return the content body as an InputStream
 */
public static InputStream getInputStream(Response response) {
    try {
        return response.body().byteStream();
    } catch (final IOException e) {
        log.log(Level.SEVERE, ERROR_MESSAGE, e);
        throw new RuntimeException(ERROR_MESSAGE, e);
    }
}

From source file:com.ibm.watson.developer_cloud.util.ResponseUtil.java

License:Open Source License

/**
 * Return a {@link JsonElement} representation of the response.
 * /*w  w w.  ja v a2  s .c  om*/
 * @param response the Response
 * @return the content body as JSON
 */
public static JsonElement getJsonElement(Response response) {
    try {
        return new JsonParser().parse(response.body().charStream());
    } catch (final IOException e) {
        log.log(Level.SEVERE, ERROR_MESSAGE, e);
        throw new RuntimeException(ERROR_MESSAGE, e);
    }
}

From source file:com.ibm.watson.developer_cloud.util.ResponseUtil.java

License:Open Source License

/**
 * Parses the response into the POJO representation
 * /*  w  ww . ja v a  2 s . com*/
 * @param <T> the generic type to use when parsing the response
 * @param response the HTTP response
 * @param type the type of the response
 * @return the POJO
 */
public static <T extends GenericModel> T getObject(Response response, Class<T> type) {
    try {
        Reader bodyCharStream = response.body().charStream();
        //      PrintingReaderWrapper printingReaderWrapper = new PrintingReaderWrapper(bodyCharStream);
        final T model = GsonSingleton.getGson().fromJson(new JsonReader(bodyCharStream), type);
        return model;
    } catch (IOException e) {
        log.log(Level.SEVERE, ERROR_MESSAGE, e);
        throw new RuntimeException(ERROR_MESSAGE, e);
    } finally {
        try {
            response.body().close();
        } catch (IOException e) {
            log.log(Level.SEVERE, "Error closing the HTTP Response", e);
        }
    }
}

From source file:com.ibm.watson.developer_cloud.util.ResponseUtil.java

License:Open Source License

/**
 * Returns a String representation of the response.
 * /*from w ww.  j  ava  2  s .  com*/
 * @param response an HTTP response
 * @return the content body as String
 */
public static String getString(Response response) {
    try {
        return response.body().string();
    } catch (final IOException e) {
        log.log(Level.SEVERE, ERROR_MESSAGE, e);
        throw new RuntimeException(ERROR_MESSAGE, e);
    }
}

From source file:com.inductiveautomation.ignition.examples.reporting.datasource.common.RestJsonDataSource.java

/**
 * Attempts to connect to a Url using {@link OkHttpClient} and return the body of the reply as a String, if it is
 * JSON mime type.//from w ww  .j a v  a 2  s  . c  o m
 * @param url String specifying the
 * @return the body of the http response received from the specified Url
 */
private String collectData(String url) throws IOException {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();

    Response response = client.newCall(request).execute();

    // get headers to check the content type out of
    Headers headers = null;
    if (response != null) {
        headers = response.headers();
    }

    // at least try to make sure we have JSON data.
    boolean isJSON = false;
    if (headers != null) {
        isJSON = MediaType.parse(headers.get("Content-Type")).equals(JSON);
    }

    return isJSON ? response.body().string() : "";
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

License:Open Source License

private void sendRequest(BaseRequest request, @Nonnull Request.Builder builder, String requestBody,
        String method) {/*from   w  ww  .j  a v  a  2  s.c  o m*/
    String uri = null;
    long waitTime = 0L;
    try {
        setHeaders(request, builder, request.getHeaderInformation());

        List<String> cookies = new ArrayList<String>();
        if (((CookieManager) okHttpClient.getCookieHandler()).getCookieStore().getCookies() != null) {
            for (HttpCookie httpCookie : ((CookieManager) okHttpClient.getCookieHandler()).getCookieStore()
                    .getCookies()) {
                cookies.add("REQUEST COOKIE: " + httpCookie.toString());
            }
        }

        Request okRequest = builder.build();
        uri = okRequest.uri().toString();
        LOG.debug(request.getLogUtil().getLogMessage(
                "About to " + okRequest.method() + " request to " + uri + " with requestBody  " + requestBody,
                LogEventType.Informational));
        request.logRequest(uri, requestBody, okRequest.method(), request.getHeaderInformation(), cookies,
                false);

        Response response = okHttpClient.newCall(okRequest).execute();
        long startTime = Long.parseLong(response.header("OkHttp-Sent-Millis"));
        long endTime = Long.parseLong(response.header("OkHttp-Sent-Millis"));

        // read response body
        byte[] responseBody = new byte[0];
        // check for no content headers
        if (response.code() != 203 && response.code() != 202 && response.code() != 204) {
            try {
                responseBody = response.body().bytes();
            } catch (Exception e) {
                LOG.warn("could not get response body: " + e);
            }
        }

        processResponse(responseBody, startTime, endTime, request, response.message(), response.code(),
                response.headers());
        waitTime = endTime - startTime;
    } catch (Exception ex) {
        LOG.error(request.getLogUtil().getLogMessage(
                "Could not do " + method + " to url " + uri + " |  error: " + ex.toString(), LogEventType.IO),
                ex);
        throw new RuntimeException(ex);
    } finally {
        if (method.equalsIgnoreCase("post") && request.getLogUtil().getAgentConfig().getLogPostResponse()) {
            LOG.info(request.getLogUtil()
                    .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code "
                            + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody()
                            + " }", LogEventType.Informational));
        }
    }
    if (waitTime != 0) {
        doWaitDueToLongResponse(request, waitTime, uri);
    }
}

From source file:com.j1024.mcommon.network.Http.java

License:Open Source License

public static void get(final String url, final StringCallback callback) {
    L.d(TAG, "Do GET --> " + url);
    final Request request = new Request.Builder().url(url).tag(url).build();
    client.newCall(request).enqueue(new Callback() {
        @Override//from  w  ww  .  ja  v  a  2  s.  c om
        public void onFailure(final Request request, final IOException e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onFailure(request, ResultCode.NetworkException, e);
                }
            });
        }

        @Override
        public void onResponse(Response response) {
            try {
                final String responseString = response.body().string();
                L.v(TAG, "[" + url + "] response:" + responseString);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onResponse(responseString);
                    }
                });
            } catch (final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(request, ResultCode.NetworkException, e);
                    }
                });
            } catch (final JsonSyntaxException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(request, ResultCode.ServerException, e);
                    }
                });
            }
        }
    });
}