Example usage for com.squareup.okhttp Response priorResponse

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

Introduction

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

Prototype

Response priorResponse

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

Click Source Link

Usage

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

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
    Request request = response.request();

    if (host != null && !request.httpUrl().host().equalsIgnoreCase(host)) {
        Constants.log.warn("Not authenticating against " + host + " for security reasons!");
        return null;
    }//from  w ww  .  j  a  v  a 2  s .  c  o m

    // check whether this is the first authentication try with our credentials
    Response priorResponse = response.priorResponse();
    boolean triedBefore = priorResponse != null ? priorResponse.request().header(HEADER_AUTHORIZATION) != null
            : false;

    HttpUtils.AuthScheme basicAuth = null, digestAuth = null;
    for (HttpUtils.AuthScheme scheme : HttpUtils
            .parseWwwAuthenticate(response.headers(HEADER_AUTHENTICATE).toArray(new String[0])))
        if ("Basic".equalsIgnoreCase(scheme.name))
            basicAuth = scheme;
        else if ("Digest".equalsIgnoreCase(scheme.name))
            digestAuth = scheme;

    // we MUST prefer Digest auth [https://tools.ietf.org/html/rfc2617#section-4.6]
    if (digestAuth != null) {
        // Digest auth

        if (triedBefore && !"true".equalsIgnoreCase(digestAuth.params.get("stale")))
            // credentials didn't work last time, and they won't work now -> stop here
            return null;
        return authorizationRequest(request, digestAuth);

    } else if (basicAuth != null) {
        // Basic auth
        if (triedBefore) // credentials didn't work last time, and they won't work now -> stop here
            return null;

        return request.newBuilder().header(HEADER_AUTHORIZATION, Credentials.basic(username, password)).build();
    }

    // no supported auth scheme
    return null;
}

From source file:com.cuddlesoft.norilib.service.ServiceTypeDetectionService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Extract SearchClient.Settings from the received Intent.
    final Uri uri = Uri.parse(intent.getStringExtra(ENDPOINT_URL));
    final Intent broadcastIntent = new Intent(ACTION_DONE);

    if (uri.getHost() == null || uri.getScheme() == null) {
        // The URL supplied is invalid.
        sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_INVALID_URL));
        return;//from   w w  w  . j  a v  a  2s.c  o  m
    }

    // Create the HTTP client.
    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS);
    okHttpClient.setReadTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS);

    // Iterate over supported URI schemes for given URL.
    for (String uriScheme : (TLS_SUPPORT.contains(uri.getHost()) ? URI_SCHEMES_PREFER_SSL : URI_SCHEMES)) {
        String baseUri = uriScheme + uri.getHost();
        // Iterate over each endpoint path.
        for (Map.Entry<SearchClient.Settings.APIType, String> entry : API_ENDPOINT_PATHS.entrySet()) {
            // Create a HTTP request object.
            final Request request = new Request.Builder().url(baseUri + entry.getValue()).build();

            try {
                // Fetch response.
                final Response response = okHttpClient.newCall(request).execute();
                // Make sure the response code was OK and that the HTTP client wasn't redirected along the way.
                if (response.code() == HttpStatus.SC_OK && response.priorResponse() == null) {
                    // Found an API endpoint.
                    broadcastIntent.putExtra(RESULT_CODE, RESULT_OK);
                    broadcastIntent.putExtra(ENDPOINT_URL, baseUri);
                    broadcastIntent.putExtra(API_TYPE, entry.getKey().ordinal());
                    sendBroadcast(broadcastIntent);
                    return;
                }
            } catch (IOException e) {
                // Network error. Notify the listeners and return.
                sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_NETWORK));
                return;
            }
        }
    }

    // End of the loop was reached without finding an API endpoint. Send error code to the BroadcastReceiver.
    sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_NO_API));
}

From source file:com.digi.wva.internal.HttpClient.java

License:Mozilla Public License

/**
 * Log information of OkHttp Response objects
 *
 * <p>This method is protected, rather than private, due to a bug between JaCoCo and
 * the Android build tools which causes the instrumented bytecode to be invalid when this
 * method is private:/*from   w  w  w.  j  av  a  2s .c  o  m*/
 * <a href="http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode" target="_blank">see StackOverflow question.</a>
 * </p>
 * @param response the HTTP response object to log
 */
protected void logResponse(Response response) {
    if (!doLogging) {
        // Logging is disabled - do nothing.
        return;
    }

    Request request = response.request();

    StringBuilder log = new StringBuilder();
    log.append(
            // e.g. <-- 200 GET /ws/hw/leds/foo
            String.format("\u2190 %d %s %s", response.code(), request.method(), request.urlString()));

    // Add on lines tracking any redirects that occurred.
    Response prior = response.priorResponse();
    if (prior != null) {
        // Call out that there were prior responses.
        log.append(" (prior responses below)");

        // Add a line to the log message for each prior response.
        // (For most if not all responses, there will likely be just one.)
        do {
            log.append(String.format("\n... prior response: %d %s %s", prior.code(), prior.request().method(),
                    prior.request().urlString()));

            // If this is a redirect, log the URL we're being redirected to.
            if (prior.isRedirect()) {
                log.append(", redirecting to ");
                log.append(prior.header("Location", "[no Location header found?!]"));
            }

            prior = prior.priorResponse();
        } while (prior != null);
    }

    Log.i(TAG, log.toString());
}

From source file:io.fabric8.openshift.client.internal.OpenShiftOAuthInterceptor.java

License:Apache License

private String authorize() {
    try {/* w ww. ja va 2s.c om*/
        OkHttpClient clone = client.clone();
        clone.interceptors().remove(this);

        String credential = Credentials.basic(config.getUsername(), new String(config.getPassword()));
        URL url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZE_PATH));
        Response response = clone
                .newCall(new Request.Builder().get().url(url).header(AUTHORIZATION, credential).build())
                .execute();
        response.body().close();
        String token = response.priorResponse().networkResponse().header(LOCATION);
        token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length());
        token = token.substring(0, token.indexOf(AFTER_TOKEN));
        return token;
    } catch (Exception e) {
        throw KubernetesClientException.launderThrowable(e);
    }
}