Example usage for com.squareup.okhttp Response header

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

Introduction

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

Prototype

public String header(String name) 

Source Link

Usage

From source file:com.mobimvp.cliques.util.StethoInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    String requestId = String.valueOf(mNextRequestId.getAndIncrement());
    Request request = chain.request();
    int requestSize = 0;
    if (mEventReporter.isEnabled()) {
        OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request);
        mEventReporter.requestWillBeSent(inspectorRequest);
        byte[] requestBody = inspectorRequest.body();
        if (requestBody != null) {
            requestSize += requestBody.length;
        }/*from   www.ja va 2 s. com*/
    }

    Response response;
    try {
        response = chain.proceed(request);
    } catch (IOException e) {
        if (mEventReporter.isEnabled()) {
            mEventReporter.httpExchangeFailed(requestId, e.toString());
        }
        throw e;
    }

    if (mEventReporter.isEnabled()) {
        if (requestSize > 0) {
            mEventReporter.dataSent(requestId, requestSize, requestSize);
        }

        Connection connection = chain.connection();
        mEventReporter
                .responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection));

        ResponseBody body = response.body();
        MediaType contentType = null;
        InputStream responseStream = null;
        if (body != null) {
            contentType = body.contentType();
            responseStream = body.byteStream();
        }

        responseStream = mEventReporter.interpretResponseStream(requestId,
                contentType != null ? contentType.toString() : null, response.header("Content-Encoding"),
                responseStream, new DefaultResponseHandler(mEventReporter, requestId));
        if (responseStream != null) {
            response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build();
        }
    }

    return response;
}

From source file:com.mozillaonline.providers.downloads.DownloadThread.java

License:Apache License

/**
 * Handle a 503 Service Unavailable status by processing the Retry-After
 * header./*from   w  w  w. j a  v  a  2 s. c om*/
 */
private void handleServiceUnavailable(State state, Response response) throws StopRequest {
    if (Constants.LOGVV) {
        Log.v(Constants.TAG, "got HTTP response code 503");
    }
    state.mCountRetry = true;
    String retryAfter = response.header("Retry-After");
    if (retryAfter != null) {
        try {
            if (Constants.LOGVV) {
                Log.v(Constants.TAG, "Retry-After :" + retryAfter);
            }
            state.mRetryAfter = Integer.parseInt(retryAfter);
            if (state.mRetryAfter < 0) {
                state.mRetryAfter = 0;
            } else {
                if (state.mRetryAfter < Constants.MIN_RETRY_AFTER) {
                    state.mRetryAfter = Constants.MIN_RETRY_AFTER;
                } else if (state.mRetryAfter > Constants.MAX_RETRY_AFTER) {
                    state.mRetryAfter = Constants.MAX_RETRY_AFTER;
                }
                state.mRetryAfter += Helpers.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
                state.mRetryAfter *= 1000;
            }
        } catch (NumberFormatException ex) {
            // ignored - retryAfter stays 0 in this case.
        }
    }
    throw new StopRequest(Downloads.STATUS_WAITING_TO_RETRY, "got 503 Service Unavailable, will retry later");
}

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/* www  .  j  a v  a 2 s  .c om*/
    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.phattn.vnexpressnews.io.OkHttpStack.java

License:Open Source License

private static HttpEntity entityFromOkHttpResponse(Response response) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();
    ResponseBody body = response.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(response.header("Content-Encoding"));

    if (body.contentType() != null) {
        entity.setContentType(body.contentType().type());
    }//from w w w . j  ava  2  s.c om
    return entity;
}

From source file:com.shekhargulati.reactivex.docker.client.DefaultRxDockerClient.java

License:Open Source License

@Override
public ContainerArchiveInformation containerArchiveInformation(final String containerId, final String path) {
    Response response = containerArchiveInformationObs(containerId, path).toBlocking().last();
    String containerInfo = response.header("X-Docker-Container-Path-Stat");

    final String containerInfoJson = new String(Base64.getDecoder().decode(containerInfo),
            Charset.defaultCharset());
    return gson.fromJson(containerInfoJson, ContainerArchiveInformation.class);
}

From source file:com.taobao.weex.devtools.inspector.network.OkHttpInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    String requestId = String.valueOf(mNextRequestId.getAndIncrement());

    Request request = chain.request();

    RequestBodyHelper requestBodyHelper = null;
    if (mEventReporter.isEnabled()) {
        requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId);
        OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request,
                requestBodyHelper);//from   w  w w. j  a  v a2  s . co  m
        mEventReporter.requestWillBeSent(inspectorRequest);
    }

    Response response;
    try {
        response = chain.proceed(request);
    } catch (IOException e) {
        if (mEventReporter.isEnabled()) {
            mEventReporter.httpExchangeFailed(requestId, e.toString());
        }
        throw e;
    }

    if (mEventReporter.isEnabled()) {
        if (requestBodyHelper != null && requestBodyHelper.hasBody()) {
            requestBodyHelper.reportDataSent();
        }

        Connection connection = chain.connection();
        mEventReporter
                .responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection));

        ResponseBody body = response.body();
        MediaType contentType = null;
        InputStream responseStream = null;
        if (body != null) {
            contentType = body.contentType();
            responseStream = body.byteStream();
        }

        responseStream = mEventReporter.interpretResponseStream(requestId,
                contentType != null ? contentType.toString() : null, response.header("Content-Encoding"),
                responseStream, new DefaultResponseHandler(mEventReporter, requestId));
        if (responseStream != null) {
            response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build();
        }
    }

    return response;
}

From source file:com.uber.sdk.rides.client.internal.RetrofitUberRidesClient.java

License:Open Source License

/**
 * Builds a RestAdapter./*from w w  w.  j a  v  a  2s .  c  om*/
 */
private static RestAdapter buildRestAdapter(final Session session, String endpointHost,
        final OAuth2Helper oAuth2Helper, RestAdapter.LogLevel logLevel, OkHttpClient httpClient)
        throws IOException {

    RequestInterceptor requestInterceptor = new RequestInterceptor() {

        @Override
        public void intercept(RequestFacade requestFacade) {
            Credential credential = session.getCredential();
            if (credential != null) {
                oAuth2Helper.refreshCredentialIfNeeded(credential);
                requestFacade.addHeader("Authorization", "Bearer " + credential.getAccessToken());
            } else {
                requestFacade.addHeader("Authorization", "Token " + session.getServerToken());
            }

            if (session.getLocale() != null) {
                requestFacade.addHeader("Accept-Language", session.getLocale().getLanguage());
            }

            requestFacade.addHeader("X-Uber-User-Agent", "Java Rides SDK v" + LIB_VERSION);
        }
    };

    if (httpClient == null) {
        httpClient = new OkHttpClient();
        httpClient.setConnectTimeout(1, TimeUnit.MINUTES);
        httpClient.setReadTimeout(1, TimeUnit.MINUTES);
        httpClient.setFollowRedirects(false);
        httpClient.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request oldRequest = chain.request();
                Response response = chain.proceed(oldRequest);
                if (response.isRedirect()) {
                    String redirectUrl = response.header(HttpHeaders.LOCATION);
                    Request newRequest = oldRequest.newBuilder().url(redirectUrl).build();
                    return chain.proceed(newRequest);
                }
                return response;
            }
        });
    }

    return new RestAdapter.Builder().setEndpoint(endpointHost)
            .setConverter(new GsonConverter(new GsonBuilder().create()))
            .setRequestInterceptor(requestInterceptor).setClient(new OkClient(httpClient)).setLogLevel(logLevel)
            .build();
}

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 av  a 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:de.feike.tiingoclient.ApiClient.java

License:Apache License

/**
 * Prepare file for download//from   w  w w . j a v  a  2  s.c o m
 *
 * @param response
 *            An instance of the Response object
 * @throws IOException
 *             If fail to prepare file for download
 * @return Prepared file for the download
 */
public File prepareDownloadFile(Response response) throws IOException {
    String filename = null;
    String contentDisposition = response.header("Content-Disposition");
    if (contentDisposition != null && !"".equals(contentDisposition)) {
        // Get filename from the Content-Disposition header.
        Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?");
        Matcher matcher = pattern.matcher(contentDisposition);
        if (matcher.find()) {
            filename = sanitizeFilename(matcher.group(1));
        }
    }

    String prefix = null;
    String suffix = null;
    if (filename == null) {
        prefix = "download-";
        suffix = "";
    } else {
        int pos = filename.lastIndexOf(".");
        if (pos == -1) {
            prefix = filename + "-";
        } else {
            prefix = filename.substring(0, pos) + "-";
            suffix = filename.substring(pos);
        }
        // File.createTempFile requires the prefix to be at least three
        // characters long
        if (prefix.length() < 3)
            prefix = "download-";
    }

    if (tempFolderPath == null)
        return File.createTempFile(prefix, suffix);
    else
        return File.createTempFile(prefix, suffix, new File(tempFolderPath));
}

From source file:dulleh.akhyou.Utils.CloudflareHttpClient.java

License:Open Source License

public Response execute(Request request) throws IOException, CloudflareException {
    Response resp = client.newCall(request).execute();
    String refresh = resp.header("Refresh");
    String server = resp.header("Server");

    List<HttpCookie> cookies = cookieManager.getCookieStore().get(request.uri());
    boolean hasCookie = Stream.of(cookies).anyMatch(c -> c.getName().equals("cf_clearance"));

    if (hasCookie)
        return resp;

    if (forceSolve) {
        return solveCloudflare(resp);
    } else if (refresh != null && refresh.contains("URL=/cdn-cgi/") && server != null
            && server.equals("cloudflare-nginx")) {

        //System.out.println("solving cloudflare");
        return solveCloudflare(resp);
    }/*from w ww.j  a  v a 2s  . c om*/

    return resp;
}