Example usage for com.squareup.okhttp Response code

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

Introduction

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

Prototype

int code

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

Click Source Link

Usage

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Deserialize response body to Java object, according to the return type and
 * the Content-Type response header.//from w  w w  . j a  v  a2  s  .  c om
 *
 * @param <T> Type
 * @param response HTTP response
 * @param returnType The type of the Java object
 * @return The deserialized Java object
 * @throws ApiException If fail to deserialize response body, i.e. cannot read response body
 *   or the Content-Type of the response is not supported.
 */
@SuppressWarnings("unchecked")
public <T> T deserialize(Response response, Type returnType) throws ApiException {
    if (response == null || returnType == null) {
        return null;
    }

    if ("byte[]".equals(returnType.toString())) {
        // Handle binary response (byte array).
        try {
            return (T) response.body().bytes();
        } catch (IOException e) {
            throw new ApiException(e);
        }
    } else if (returnType.equals(File.class)) {
        // Handle file downloading.
        return (T) downloadFileFromResponse(response);
    }

    String respBody;
    try {
        if (response.body() != null)
            respBody = response.body().string();
        else
            respBody = null;
    } catch (IOException e) {
        throw new ApiException(e);
    }

    if (respBody == null || "".equals(respBody)) {
        return null;
    }

    String contentType = response.headers().get("Content-Type");
    if (contentType == null) {
        // ensuring a default content type
        contentType = "application/json";
    }
    if (isJsonMime(contentType)) {
        return json.deserialize(respBody, returnType);
    } else if (returnType.equals(String.class)) {
        // Expecting string, return the raw response body.
        return (T) respBody;
    } else {
        throw new ApiException("Content type \"" + contentType + "\" is not supported for type: " + returnType,
                response.code(), response.headers().toMultimap(), respBody);
    }
}

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Execute HTTP call and deserialize the HTTP response body into the given return type.
 *
 * @param returnType The return type used to deserialize HTTP response body
 * @param <T> The return type corresponding to (same with) returnType
 * @param call Call/* w  w  w .  j av  a2 s . c o m*/
 * @return ApiResponse object containing response status, headers and
 *   data, which is a Java object deserialized from response body and would be null
 *   when returnType is null.
 * @throws ApiException If fail to execute the call
 */
public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException {
    try {
        Response response = call.execute();
        T data = handleResponse(response, returnType);
        return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data);
    } catch (IOException e) {
        throw new ApiException(e);
    }
}

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Execute HTTP call asynchronously./*from   w w  w  .  jav a 2  s .  com*/
 *
 * @see #execute(Call, Type)
 * @param <T> Type
 * @param call The callback to be executed when the API call finishes
 * @param returnType Return type
 * @param callback ApiCallback
 */
@SuppressWarnings("unchecked")
public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) {
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            callback.onFailure(new ApiException(e), 0, null);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            T result;
            try {
                result = (T) handleResponse(response, returnType);
            } catch (ApiException e) {
                callback.onFailure(e, response.code(), response.headers().toMultimap());
                return;
            }
            callback.onSuccess(result, response.code(), response.headers().toMultimap());
        }
    });
}

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/*from  w w  w .ja  v a2s . co 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);
    }//  ww  w  .  ja  va2s. 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();/* www  .ja  va 2 s . 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: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  va2 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:at.bitfire.dav4android.DavResource.java

License:Open Source License

protected void checkStatus(Response response) throws HttpException {
    checkStatus(response.code(), response.message(), response);
}

From source file:at.bitfire.dav4android.DavResource.java

License:Open Source License

protected void assertMultiStatus(Response response) throws DavException {
    if (response.code() != 207)
        throw new InvalidDavResponseException("Expected 207 Multi-Status");

    if (response.body() == null)
        throw new InvalidDavResponseException("Received multi-status response without body");

    MediaType mediaType = response.body().contentType();
    if (mediaType != null) {
        if (!("application".equals(mediaType.type()) || "text".equals(mediaType.type()))
                || !"xml".equals(mediaType.subtype()))
            throw new InvalidDavResponseException("Received non-XML 207 Multi-Status");
    } else//  ww  w .ja va 2 s  .com
        log.warn("Received multi-status response without Content-Type, assuming XML");
}

From source file:at.bitfire.dav4android.exception.HttpException.java

License:Open Source License

public HttpException(Response response) {
    super(response.code() + " " + response.message());

    status = response.code();/*from w  w w . j  a va 2  s.c o m*/
    message = response.message();

    /* As we don't know the media type and character set of request and response body,
       only printable ASCII characters will be shown in clear text. Other octets will
       be shown as "[xx]" where xx is the hex value of the octet.
     */

    // format request
    Request request = response.request();
    StringBuilder formatted = new StringBuilder();
    formatted.append(request.method() + " " + request.urlString() + "\n");
    Headers headers = request.headers();
    for (String name : headers.names())
        for (String value : headers.values(name))
            formatted.append(name + ": " + value + "\n");
    if (request.body() != null)
        try {
            formatted.append("\n");
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            while (!buffer.exhausted())
                appendByte(formatted, buffer.readByte());
        } catch (IOException e) {
        }
    this.request = formatted.toString();

    // format response
    formatted = new StringBuilder();
    formatted.append(response.protocol() + " " + response.code() + " " + response.message() + "\n");
    headers = response.headers();
    for (String name : headers.names())
        for (String value : headers.values(name))
            formatted.append(name + ": " + value + "\n");
    if (response.body() != null)
        try {
            formatted.append("\n");
            for (byte b : response.body().bytes())
                appendByte(formatted, b);
        } catch (IOException e) {
        }
    this.response = formatted.toString();
}