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.yandex.disk.rest.LoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    String hash = Integer.toHexString(chain.hashCode());
    String sendPrefix = hash + SEND_PREFIX;
    String receivePrefix = hash + RECEIVE_PREFIX;

    if (logWire) {
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            logger.info(sendPrefix + "request: " + requestBody);
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            byte[] requestBuffer = ByteStreams.toByteArray(buffer.inputStream());
            logBuffer(sendPrefix, requestBuffer);
        }//  w  w  w.ja v a  2 s .co m
        request = request.newBuilder().removeHeader("Accept-Encoding").addHeader("Accept-Encoding", "").build();
    }

    logger.info(sendPrefix + request.method() + " " + request.url());
    logger.info(sendPrefix + "on " + chain.connection());
    logHeaders(sendPrefix, request.headers());

    Response response = chain.proceed(request);
    logger.info(receivePrefix + response.protocol() + " " + response.code() + " " + response.message());
    logHeaders(receivePrefix, response.headers());

    if (logWire) {
        ResponseBody body = response.body();
        byte[] responseBuffer = ByteStreams.toByteArray(body.byteStream());
        response = response.newBuilder().body(ResponseBody.create(body.contentType(), responseBuffer)).build();
        logBuffer(receivePrefix, responseBuffer);
    }

    return response;
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

void downloadUrl(final String url, final DownloadListener downloadListener)
        throws IOException, CancelledDownloadException, DownloadNoSpaceAvailableException, HttpCodeException {

    Request.Builder req = buildRequest().url(url);

    long length = downloadListener.getLocalLength();
    String ifTag = "If-None-Match";
    if (length >= 0) {
        ifTag = "If-Range";
        StringBuilder contentRange = new StringBuilder();
        contentRange.append("bytes=").append(length).append("-");
        logger.debug("Range: " + contentRange);
        req.addHeader("Range", contentRange.toString());
    }//from   w  w w.  j a  va  2 s . c o  m

    String etag = downloadListener.getETag();
    if (etag != null) {
        logger.debug(ifTag + ": " + etag);
        req.addHeader(ifTag, etag);
    }

    Request request = req.build();
    Response response = client.newCall(request).execute();

    boolean partialContent = false;
    int code = response.code();
    switch (code) {
    case 200:
        // OK
        break;
    case 206:
        partialContent = true;
        break;
    case 304:
        throw new FileNotModifiedException(code);
    case 404:
        throw new NotFoundException(code);
    case 416:
        throw new RangeNotSatisfiableException(code);
    default:
        throw new HttpCodeException(code);
    }

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    logger.debug("download: contentLength=" + contentLength);

    long loaded;
    if (partialContent) {
        ContentRangeResponse contentRangeResponse = parseContentRangeHeader(response.header("Content-Range"));
        logger.debug("download: contentRangeResponse=" + contentRangeResponse);
        if (contentRangeResponse != null) {
            loaded = contentRangeResponse.getStart();
            contentLength = contentRangeResponse.getSize();
        } else {
            loaded = length;
        }
    } else {
        loaded = 0;
        if (contentLength < 0) {
            contentLength = 0;
        }
    }

    OutputStream os = null;
    try {
        downloadListener.setStartPosition(loaded);
        MediaType contentTypeHeader = responseBody.contentType();
        if (contentTypeHeader != null) {
            downloadListener.setContentType(contentTypeHeader.toString());
        }
        downloadListener.setContentLength(contentLength);

        int count;
        InputStream content = responseBody.byteStream();
        os = downloadListener.getOutputStream(partialContent);
        final byte[] downloadBuffer = new byte[1024];
        while ((count = content.read(downloadBuffer)) != -1) {
            if (downloadListener.hasCancelled()) {
                logger.info("Downloading " + url + " canceled");
                client.cancel(request.tag());
                throw new CancelledDownloadException();
            }
            os.write(downloadBuffer, 0, count);
            loaded += count;
            downloadListener.updateProgress(loaded, contentLength);
        }
    } catch (CancelledDownloadException ex) {
        throw ex;
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        client.cancel(request.tag());
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else if (e instanceof DownloadNoSpaceAvailableException) {
            throw (DownloadNoSpaceAvailableException) e;
        } else {
            // never happen
            throw new RuntimeException(e);
        }
    } finally {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException ex) {
            // nothing
        }
        try {
            response.body().close();
        } catch (IOException | NullPointerException ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

void uploadFile(final String url, final File file, final long startOffset,
        final ProgressListener progressListener) throws IOException, HttpCodeException {
    logger.debug("uploadFile: put to url: " + url);
    MediaType mediaType = MediaType.parse("application/octet-stream");
    RequestBody requestBody = RequestBodyProgress.create(mediaType, file, startOffset, progressListener);
    Request.Builder requestBuilder = buildRequest().removeHeader(Credentials.AUTHORIZATION_HEADER).url(url)
            .put(requestBody);//from   ww w  .j a va2s  .com
    if (startOffset > 0) {
        StringBuilder contentRange = new StringBuilder();
        contentRange.append("bytes ").append(startOffset).append("-").append(file.length() - 1).append("/")
                .append(file.length());
        logger.debug(CONTENT_RANGE_HEADER + ": " + contentRange);
        requestBuilder.addHeader(CONTENT_RANGE_HEADER, contentRange.toString());
    }
    Request request = requestBuilder.build();

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

    String statusLine = response.message();
    logger.debug("headUrl: " + statusLine + " for url " + url);

    int code = response.code();

    ResponseBody responseBody = response.body();
    responseBody.close();

    switch (code) {
    case 201:
    case 202:
        logger.debug("uploadFile: file uploaded successfully: " + file);
        break;
    case 404:
        throw new NotFoundException(code, null);
    case 409:
        throw new ConflictException(code, null);
    case 412:
        throw new PreconditionFailedException(code, null);
    case 413:
        throw new FileTooBigException(code, null);
    case 503:
        throw new ServiceUnavailableException(code, null);
    case 507:
        throw new InsufficientStorageException(code, null);
    default:
        throw new HttpCodeException(code);
    }
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

long getUploadedSize(String url, Hash hash) throws IOException {

    Request request = buildRequest().removeHeader(Credentials.AUTHORIZATION_HEADER).url(url).head()
            .addHeader(ETAG_HEADER, hash.getMd5()).addHeader(SHA256_HEADER, hash.getSha256())
            .addHeader(SIZE_HEADER, String.valueOf(hash.getSize())).build();

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

    int code = response.code();
    ResponseBody responseBody = response.body();
    responseBody.close();/*from ww w. j  av a  2s.  c o  m*/
    switch (code) {
    case 200:
        return Long.valueOf(response.header(CONTENT_LENGTH_HEADER, "0"));
    default:
        return 0;
    }
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

Operation getOperation(String url) throws IOException, HttpCodeException {
    Response response = call(METHOD_GET, url);
    int code = response.code();
    if (!response.isSuccessful()) {
        throw new HttpCodeException(code);
    }//  ww  w.  j  a  v a 2s  . c  o  m
    return parseJson(response, Operation.class);
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

Link delete(String url) throws IOException, ServerIOException {
    Response response = null;
    try {/*  w  w  w.  j  a  v  a  2s. c o m*/
        response = call(METHOD_DELETE, url);
        switch (response.code()) {
        case 202:
            Link result = parseJson(response, Link.class);
            result.setHttpStatus(Link.HttpStatus.inProgress);
            return result;
        case 204:
            close(response);
            return Link.DONE;
        default:
            throw ErrorHandlerImpl.createHttpCodeException(response.code(), response.body().byteStream());
        }
    } finally {
        close(response);
    }
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

Link put(String url) throws IOException, ServerIOException {
    Response response = null;
    try {/*w w  w  .ja va2  s  .c o m*/
        response = call(METHOD_PUT, url);
        switch (response.code()) {
        case 201:
            Link done = parseJson(response, Link.class);
            done.setHttpStatus(Link.HttpStatus.done);
            return done;
        case 202:
            Link inProgress = parseJson(response, Link.class);
            inProgress.setHttpStatus(Link.HttpStatus.inProgress);
            return inProgress;
        default:
            throw ErrorHandlerImpl.createHttpCodeException(response.code(), response.body().byteStream());
        }
    } finally {
        close(response);
    }
}

From source file:com.ydh.gva.util.net.volley.toolbox.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();
    okHttpRequestBuilder.addHeader("clientos", "101");
    okHttpRequestBuilder.addHeader("osversion", SystemVal.sdk + "");
    okHttpRequestBuilder.addHeader("clientphone", SystemVal.model + "");
    okHttpRequestBuilder.addHeader("weiLeversion", SystemVal.versionCode + "");

    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/*from ww w .ja  v a2 s.  com*/

    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:de.dev.eth0.rssreader.core.http.callback.AbstractFeedLoaderCallback.java

License:Apache License

@Override
public void onResponse(Response response) throws IOException {
    Timber.d("onSuccess %d (cache: %s network: %s)", response.code(), response.cacheResponse(),
            response.networkResponse());
    if (response.isSuccessful() && response.networkResponse() != null
            && response.networkResponse().code() != HttpURLConnection.HTTP_NOT_MODIFIED) {
        List<FeedEntry> summaries = RssFeedParser.parseFeed(response.body().byteStream());
        DataProviderHelper helper = getDataProviderHelper();
        List<FeedEntry> added = helper.insertFeedEntry(summaries);
        getNotificationManger().sendFeedUpdatedNotification(added);

        getPrecacheHelper().precache(summaries);
    }/*  w  w  w  .  j  a v a 2s  .c  o  m*/
    afterCallback();
}

From source file:de.dev.eth0.rssreader.core.http.callback.PrecacheCallback.java

License:Apache License

@Override
public void onResponse(Response response) throws IOException {
    Timber.d("onSuccess %d (cache: %s network: %s)", response.code(), response.cacheResponse(),
            response.networkResponse());
}