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:com.parse.ParseOkHttpClient.java

License:Open Source License

@Override
/* package */ ParseHttpResponse getResponse(Response okHttpResponse) throws IOException {
    // Status code
    int statusCode = okHttpResponse.code();

    // Content// w  w w. j a v  a  2  s.  com
    InputStream content = okHttpResponse.body().byteStream();

    // Total size
    int totalSize = (int) okHttpResponse.body().contentLength();

    // Reason phrase
    String reasonPhrase = okHttpResponse.message();

    // Headers
    Map<String, String> headers = new HashMap<>();
    for (String name : okHttpResponse.headers().names()) {
        headers.put(name, okHttpResponse.header(name));
    }

    // Content type
    String contentType = null;
    ResponseBody body = okHttpResponse.body();
    if (body != null && body.contentType() != null) {
        contentType = body.contentType().toString();
    }

    return new ParseHttpResponse.Builder().setStatusCode(statusCode).setContent(content).setTotalSize(totalSize)
            .setReasonPhrase(reasonPhrase).setHeaders(headers).setContentType(contentType).build();
}

From source file:com.peach.masktime.module.net.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();
    LogUtils.i(TAG, "timeoutMs = " + timeoutMs);
    client.setProxy(Proxy.NO_PROXY);
    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));
    }/*from w  w  w  .  j av  a 2s  .  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.phattn.vnexpressnews.io.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));
    }/*from w  ww .j a  v a  2 s.  c  o 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, length = responseHeaders.size(); i < length; i++) {
        final String name = responseHeaders.name(i);
        final String value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

License:Open Source License

public int performCreateFeedRequest(HttpUrl url, String feedUrlString, long folderId) throws Exception {
    HttpUrl feedUrl = url.newBuilder().setQueryParameter("url", feedUrlString)
            .setQueryParameter("folderId", String.valueOf(folderId)).build();

    Request request = new Request.Builder().url(feedUrl).post(RequestBody.create(JSON, "")).build();

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

    return response.code();
}

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

License:Open Source License

public int performRemoveFeedRequest(HttpUrl url, long feedId) throws Exception {
    HttpUrl feedUrl = url.newBuilder().addPathSegment(String.valueOf(feedId)).build();

    Request request = new Request.Builder().url(feedUrl).delete().build();

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

    return response.code();
}

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

License:Open Source License

public int performRenameFeedRequest(HttpUrl url, long feedId, String newFeedName) throws Exception {
    HttpUrl feedUrl = url.newBuilder().addPathSegment(String.valueOf(feedId)).addPathSegment("rename").build();

    Request request = new Request.Builder().url(feedUrl)
            .put(RequestBody.create(JSON, new JSONObject().put("feedTitle", newFeedName).toString())).build();

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

    return response.code();
}

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

License:Open Source License

public int performTagChangeRequest(HttpUrl url, String content) throws Exception {
    Request request = new Request.Builder().url(url).put(RequestBody.create(JSON, content)).build();

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

    return response.code();
}

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

License:Open Source License

public Tuple<Integer, String> performCreateFolderRequest(HttpUrl url, String folderName) throws Exception {
    Request request = new Request.Builder().url(url)
            .post(RequestBody.create(JSON, new JSONObject().put("name", folderName).toString())).build();

    Response response = client.newCall(request).execute();
    String body = response.body().string();
    return new Tuple<>(response.code(), body);
}

From source file:com.rafagarcia.countries.backend.webapi.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 a va2  s  .com

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

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

        String endMessage = "--> END " + request.method();
        if (logBody && hasRequestBody) {
            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));
        }

        if (logBody) {
            Buffer buffer = new Buffer();
            responseBody.source().readAll(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));
            }

            // Since we consumed the original, replace the one-shot body in the response with a new one.
            response = response.newBuilder()
                    .body(ResponseBody.create(contentType, responseBody.contentLength(), buffer)).build();
        }

        String endMessage = "<-- END HTTP";
        if (logBody) {
            endMessage += " (" + responseBody.contentLength() + "-byte body)";
        }
        logger.log(endMessage);
    }

    return response;
}

From source file:com.rhc.dynamic.pipeline.DynamicPipelineFactory.java

License:Apache License

public DynamicPipelineFactory withHttpConfiguration(String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();
    if (response.code() != 200) {
        throw new RuntimeException("The http configuration returned a status code of " + response.code()
                + ". We only support 200. Here is the response message: " + response.message());
    } else {/*from   ww  w  . ja v  a2 s. c  o  m*/
        InputStream is = response.body().byteStream();
        if (is == null) {
            throw new RuntimeException("The http configuration response body is null!");
        }
        this.configFile = IOUtils.toString(is);
        LOGGER.debug(this.configFile);
        engagement = new ObjectMapper().readValue(this.configFile, Engagement.class);
    }
    return this;
}