Example usage for com.squareup.okhttp Response message

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

Introduction

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

Prototype

String message

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

Click Source Link

Usage

From source file:com.abiquo.apiclient.RestClient.java

License:Apache License

private void checkResponse(final Request request, final Response response, final String responseBody)
        throws IOException {
    int responseCode = response.code();
    if (responseCode == 401 || responseCode == 403) {
        throw new AuthorizationException(responseCode, response.message());
    } else if (responseCode >= 400) {
        if (responseBody == null) {
            throw new HttpException(responseCode, response.message());
        }/*from w ww  .ja va  2 s  .c  o  m*/

        try {
            ErrorsDto errors = json.read(responseBody, ErrorsDto.class);
            throw new AbiquoException(responseCode, errors);
        } catch (Exception ex) {
            Throwables.propagateIfInstanceOf(ex, AbiquoException.class);
            throw new HttpException(responseCode, response.message() + ". Body: " + responseBody);
        }
    }
}

From source file:com.aix.city.comm.OkHttpStack.java

License:Open Source License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/* w  w w.  j a  v  a2s.co m*/
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:com.appstarter.utils.WebUtils.java

License:Apache License

public static String doHttpGet(String url) throws AppStarterException {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "doHttpGet - url: " + url);
    }/*from w  w w  . j  a va 2s. c o m*/

    String ret = "";

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout

    try {
        Request request = new Request.Builder().url(new URL(url))
                //               .header("User-Agent", "OkHttp Headers.java")
                //               .addHeader("Accept", "application/json; q=0.5")
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            String debugMessage = "doHttpGet - OkHttp.Response is not successful - " + response.message() + " ("
                    + response.code() + ")";
            throw new AppStarterException(AppStarterException.ERROR_SERVER, debugMessage);
        }
        ret = response.body().string();
    } catch (IOException e) {
        throw new AppStarterException(e, AppStarterException.ERROR_NETWORK_GET);
    }

    return ret;
}

From source file:com.appstarter.utils.WebUtils.java

License:Apache License

public static String doHttpPost(String url, List<NameValuePair> params) throws AppStarterException {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "doHttpPost - url: " + debugRequest(url, params));
    }/* w  w w.j  a v  a2 s.  c  o m*/

    String ret = "";

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout

    FormEncodingBuilder builder = new FormEncodingBuilder();
    for (NameValuePair nvp : params) {
        builder.add(nvp.getName(), nvp.getValue());
    }
    RequestBody formBody = builder.build();

    try {
        Request request = new Request.Builder().url(new URL(url))
                //               .header("User-Agent", "OkHttp Headers.java")
                //               .addHeader("Accept", "application/json; q=0.5")
                .post(formBody).build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            String debugMessage = "doHttpPost - OkHttp.Response is not successful - " + response.message()
                    + " (" + response.code() + ")";
            throw new AppStarterException(AppStarterException.ERROR_SERVER, debugMessage);
        }
        ret = response.body().string();
    } catch (IOException e) {
        throw new AppStarterException(e, AppStarterException.ERROR_NETWORK_GET);
    }

    return ret;
}

From source file:com.ariadnext.idcheckio.invoker.ApiClient.java

License:Apache License

/**
 * Handle the given response, return the deserialized object when the response is successful.
 *
 * @param <T> Type//ww w  . j  ava2 s. c om
 * @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() || response.code() == 303) {
        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:com.baasbox.android.net.OkClient.java

License:Apache License

@Override
public HttpResponse execute(HttpRequest request) throws BaasException {
    String contentType = request.headers.get("Content-Type");
    Request.Builder okRequestBuilder = new Request.Builder();
    boolean contentLengthSet = false;
    for (String name : request.headers.keySet()) {
        if (!contentLengthSet && "Content-Length".equals(name)) {
            contentLengthSet = true;// w ww  . ja v a2s  . c  o  m
        }
        okRequestBuilder.addHeader(name, request.headers.get(name));
    }
    if (!contentLengthSet) {
        okRequestBuilder.addHeader("Content-Length", "0");
    }
    RequestBody rb;
    switch (request.method) {
    case HttpRequest.GET:
        okRequestBuilder.get();
        break;
    case HttpRequest.POST:
        rb = buildBody(contentType, request.body);
        //InputRequestBody rb = new InputRequestBody(contentType,request.body);
        okRequestBuilder.post(rb);
        break;
    case HttpRequest.PUT:
        rb = buildBody(contentType, request.body);
        okRequestBuilder.put(rb);
        break;
    case HttpRequest.DELETE:
        okRequestBuilder.delete();
        break;
    case HttpRequest.PATCH:
        rb = buildBody(contentType, request.body);
        okRequestBuilder.patch(rb);
        break;

    }

    okRequestBuilder.url(request.url);
    Request okRequest = okRequestBuilder.build();
    try {
        Response resp = mOkHttp.newCall(okRequest).execute();
        Protocol protocol = resp.protocol();
        ProtocolVersion pv;
        switch (protocol) {
        case HTTP_1_0:
            pv = new ProtocolVersion("HTTP", 1, 0);
            break;
        case HTTP_1_1:
            pv = new ProtocolVersion("HTTP", 1, 1);
            break;
        case HTTP_2:
            pv = new ProtocolVersion("HTTP", 2, 0);
            break;
        case SPDY_3:
            pv = new ProtocolVersion("spdy", 3, 1);
            break;
        default:
            throw new BaasIOException("Invalid protocol");
        }
        StatusLine line = new BasicStatusLine(pv, resp.code(), resp.message());
        BasicHttpResponse bresp = new BasicHttpResponse(line);
        bresp.setEntity(asEntity(resp));

        for (String name : resp.headers().names()) {
            String val = resp.headers().get(name);
            bresp.addHeader(name, val);
        }
        return bresp;
    } catch (IOException e) {
        throw new BaasIOException(e);
    }
}

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}.//  ww w.  jav  a  2 s .  com
 */
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.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  v a 2 s.  com
    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.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);
    }//ww  w  .  j a v a 2s . co  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() + ' ' + 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;
}

From source file:com.datastore_android_sdk.okhttp.OkHttpStack.java

License:Open Source License

private URLHttpResponse responseFromConnection(Response okHttpResponse) throws IOException {
    URLHttpResponse response = new URLHttpResponse();
    //contentStream
    int responseCode = okHttpResponse.code();
    if (responseCode == -1) {
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }/*w ww . j  av a 2s.  com*/
    response.setResponseCode(responseCode);
    response.setResponseMessage(okHttpResponse.message());

    response.setContentStream(okHttpResponse.body().byteStream());

    response.setContentLength(okHttpResponse.body().contentLength());
    response.setContentEncoding(okHttpResponse.header("Content-Encoding"));
    if (okHttpResponse.body().contentType() != null) {
        response.setContentType(okHttpResponse.body().contentType().type());
    }

    //header
    HashMap<String, String> headerMap = new HashMap<>();
    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            headerMap.put(name, value);
        }
    }
    response.setHeaders(headerMap);
    return response;
}