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:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Handle the given response, return the deserialized object when the response is successful.
 *
 * @param <T> Type//  w w  w .  j av  a2 s . c  o  m
 * @param response Response
 * @param returnType Return type
 * @throws ApiException If the response has a unsuccessful status code or
 *   fail to deserialize the response body
 * @return Type
 */
public <T> T handleResponse(Response response, Type returnType) throws ApiException {
    if (response.isSuccessful()) {
        if (returnType == null || response.code() == 204) {
            // returning null if the returnType is not defined,
            // or the status code is 204 (No Content)
            return null;
        } else {
            return deserialize(response, returnType);
        }
    } else {
        String respBody = null;
        if (response.body() != null) {
            try {
                respBody = response.body().string();
            } catch (IOException e) {
                throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
            }
        }
        throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
    }
}

From source file:alberto.avengers.model.rest.utils.interceptors.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 w  w. ja  v a2  s. c o m

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

        String endMessage = "--> END " + request.method();
        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));

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

        String endMessage = "<-- END HTTP";
        if (logBody) {
            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) {
                charset = contentType.charset(UTF8);
            }

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

            endMessage += " (" + buffer.size() + "-byte body)";
        }
        logger.log(endMessage);
    }

    return response;
}

From source file:alfio.plugin.mailchimp.MailChimpPlugin.java

License:Open Source License

private boolean send(int eventId, String address, String apiKey, String email, CustomerName name,
        String language, String eventKey) {
    Map<String, Object> content = new HashMap<>();
    content.put("email_address", email);
    content.put("status", "subscribed");
    Map<String, String> mergeFields = new HashMap<>();
    mergeFields.put("FNAME", name.isHasFirstAndLastName() ? name.getFirstName() : name.getFullName());
    mergeFields.put(ALFIO_EVENT_KEY, eventKey);
    content.put("merge_fields", mergeFields);
    content.put("language", language);
    Request request = new Request.Builder().url(address)
            .header("Authorization", Credentials.basic("alfio", apiKey))
            .put(RequestBody.create(MediaType.parse(APPLICATION_JSON), Json.GSON.toJson(content, Map.class)))
            .build();//w  w w  .  j  ava 2s . c  o  m
    try {
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            pluginDataStorage.registerSuccess(String.format("user %s has been subscribed to list", email),
                    eventId);
            return true;
        }
        String responseBody = response.body().string();
        if (response.code() != 400 || responseBody.contains("\"errors\"")) {
            pluginDataStorage.registerFailure(String.format(FAILURE_MSG, email, name, language, responseBody),
                    eventId);
            return false;
        } else {
            pluginDataStorage.registerWarning(String.format(FAILURE_MSG, email, name, language, responseBody),
                    eventId);
        }
        return true;
    } catch (IOException e) {
        pluginDataStorage.registerFailure(String.format(FAILURE_MSG, email, name, language, e.toString()),
                eventId);
        return false;
    }
}

From source file:alfio.plugin.mailchimp.MailChimpPlugin.java

License:Open Source License

private void createMergeFieldIfNotPresent(String listAddress, String apiKey, int eventId, String eventKey) {
    Request request = new Request.Builder().url(listAddress + MERGE_FIELDS)
            .header("Authorization", Credentials.basic("alfio", apiKey)).get().build();
    try {//from  w  ww . j a  v a  2  s  .  co  m
        Response response = httpClient.newCall(request).execute();
        String responseBody = response.body().string();
        if (!responseBody.contains(ALFIO_EVENT_KEY)) {
            log.debug("can't find ALFIO_EKEY for event " + eventKey);
            createMergeField(listAddress, apiKey, eventKey, eventId);
        }
    } catch (IOException e) {
        pluginDataStorage.registerFailure(
                String.format("Cannot get merge fields for %s, got: %s", eventKey, e.getMessage()), eventId);
        log.warn("exception while reading merge fields for event id " + eventId, e);
    }
}

From source file:alfio.plugin.mailchimp.MailChimpPlugin.java

License:Open Source License

private void createMergeField(String listAddress, String apiKey, String eventKey, int eventId) {

    Map<String, Object> mergeField = new HashMap<>();
    mergeField.put("tag", ALFIO_EVENT_KEY);
    mergeField.put("name", "Alfio's event key");
    mergeField.put("type", "text");
    mergeField.put("required", false);
    mergeField.put("public", false);

    Request request = new Request.Builder().url(listAddress + MERGE_FIELDS)
            .header("Authorization", Credentials.basic("alfio", apiKey)).post(RequestBody
                    .create(MediaType.parse(APPLICATION_JSON), Json.GSON.toJson(mergeField, Map.class)))
            .build();/*from   w  w  w  .jav  a2s.  co  m*/

    try {
        Response response = httpClient.newCall(request).execute();
        if (!response.isSuccessful()) {
            log.debug("can't create {} merge field. Got: {}", ALFIO_EVENT_KEY, response.body().string());
        }
    } catch (IOException e) {
        pluginDataStorage.registerFailure(
                String.format("Cannot create merge field for %s, got: %s", eventKey, e.getMessage()), eventId);
        log.warn("exception while creating ALFIO_EKEY for event id " + eventId, e);
    }
}

From source file:api.QueryManager.java

License:Open Source License

private Reader executeRequest(Request request, boolean limit) {
    // Get response
    Response response = null;
    try {//from w w w.  j  a v a2  s.  c o  m

        if (limit) {
            // Obey the rate limit
            longRateLimiter.acquire();
            shortRateLimiter.acquire();
        }

        response = client.newCall(request).execute();
    } catch (IOException e) {
        // Handle error
        throw new UltiException(UltiException.Type.UNKNOWN);
    }

    // Handle any errors
    if (!response.isSuccessful()) {
        handleErrorCode(response.code());
    }

    return response.body().charStream();
}

From source file:apijson.demo.client.manager.HttpManager.java

License:Apache License

/**
 * @param client/*from  ww  w .j a v  a2s. c o  m*/
 * @param request
 * @return
 * @throws Exception
 */
private String getResponseJson(OkHttpClient client, Request request) throws Exception {
    if (client == null || request == null) {
        Log.e(TAG, "getResponseJson  client == null || request == null >> return null;");
        return null;
    }
    Response response = client.newCall(request).execute();
    return response.isSuccessful() ? response.body().string() : null;
}

From source file:appewtc.masterung.testdrivinglicense.ScoreListView.java

private void createListView() {

    String urlPHP = "http://swiftcodingthai.com/toey/get_score_where.php";

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormEncodingBuilder().add("isAdd", "true").add("id_login", loginStrings[0])
            .build();//from  w ww  .j a v a 2  s.c om
    Request.Builder builder = new Request.Builder();
    Request request = builder.url(urlPHP).post(requestBody).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {

            String strResponse = response.body().string();
            Log.d("10AugV2", "strResponse ==> " + strResponse);

            try {

                JSONArray jsonArray = new JSONArray(strResponse);

                String[] dateStrings = new String[jsonArray.length()];
                String[] scoreStrings = new String[jsonArray.length()];

                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    dateStrings[i] = jsonObject.getString("Date");
                    scoreStrings[i] = "? = " + jsonObject.getString("Score")
                            + " ?";

                } // for

                CoaurseAdapter coaurseAdapter = new CoaurseAdapter(ScoreListView.this, 1, dateStrings,
                        scoreStrings);
                listView.setAdapter(coaurseAdapter);

            } catch (Exception e) {
                e.printStackTrace();
            }

        } // onResponse
    });

}

From source file:at.aau.itec.android.mediaplayer.dash.DashMediaExtractor.java

License:Open Source License

/**
 * Blocking download of a segment./*from  ww  w.  j  a  va  2  s  .  c o m*/
 */
private CachedSegment downloadFile(Integer segmentNr) throws IOException {
    // At the first call, download the initialization segments, and reuse them later.
    if (mInitSegments.isEmpty()) {
        for (Representation representation : mAdaptationSet.representations) {
            Request request = buildSegmentRequest(representation.initSegment);
            long startTime = SystemClock.elapsedRealtime();
            Response response = mHttpClient.newCall(request).execute();
            ByteString segmentData = response.body().source().readByteString();
            mInitSegments.put(representation, segmentData);
            mAdaptationLogic.reportSegmentDownload(mAdaptationSet, representation,
                    representation.segments.get(segmentNr), segmentData.size(),
                    SystemClock.elapsedRealtime() - startTime);
            Log.d(TAG, "init " + representation.initSegment.toString());
        }
    }

    Segment segment = mRepresentation.segments.get(segmentNr);
    Request request = buildSegmentRequest(segment);
    long startTime = SystemClock.elapsedRealtime();
    Response response = mHttpClient.newCall(request).execute();
    byte[] segmentData = response.body().bytes();
    mAdaptationLogic.reportSegmentDownload(mAdaptationSet, mRepresentation, segment, segmentData.length,
            SystemClock.elapsedRealtime() - startTime);
    CachedSegment cachedSegment = new CachedSegment(segmentNr, segment, mRepresentation);
    handleSegment(segmentData, cachedSegment);
    Log.d(TAG, "sync dl " + segmentNr + " " + segment.toString() + " -> " + cachedSegment.file.getPath());

    return cachedSegment;
}

From source file:at.aau.itec.android.mediaplayer.dash.DashParser.java

License:Open Source License

/**
 * Parses an MPD XML file. This needs to be executed off the main thread, else a
 * NetworkOnMainThreadException gets thrown.
 * @param source the URl of an MPD XML file
 * @return a MPD object//  ww  w .j av  a 2  s . c  o m
 * @throws android.os.NetworkOnMainThreadException if executed on the main thread
 */
public MPD parse(UriSource source) {
    MPD mpd = null;
    OkHttpClient httpClient = new OkHttpClient();

    Headers.Builder headers = new Headers.Builder();
    if (source.getHeaders() != null && !source.getHeaders().isEmpty()) {
        for (String name : source.getHeaders().keySet()) {
            headers.add(name, source.getHeaders().get(name));
        }
    }

    Request.Builder request = new Request.Builder().url(source.getUri().toString()).headers(headers.build());

    try {
        Response response = httpClient.newCall(request.build()).execute();
        if (!response.isSuccessful()) {
            throw new IOException("error requesting the MPD");
        }
        mpd = parse(response.body().byteStream());
    } catch (IOException e) {
        Log.e(TAG, "error downloading the MPD", e);
        throw new RuntimeException("error downloading the MPD", e);
    } catch (XmlPullParserException e) {
        Log.e(TAG, "error parsing the MPD", e);
        throw new RuntimeException("error parsing the MPD", e);
    }

    return mpd;
}