Example usage for com.squareup.okhttp Request newBuilder

List of usage examples for com.squareup.okhttp Request newBuilder

Introduction

In this page you can find the example usage for com.squareup.okhttp Request newBuilder.

Prototype

public Builder newBuilder() 

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;
    }//www.  j a  v  a  2 s.c  om

    // 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:at.bitfire.dav4android.BasicDigestAuthenticator.java

License:Open Source License

protected Request authorizationRequest(Request request, HttpUtils.AuthScheme digest) {
    String realm = digest.params.get("realm"), opaque = digest.params.get("opaque"),
            nonce = digest.params.get("nonce");

    Algorithm algorithm = Algorithm.determine(digest.params.get("algorithm"));
    Protection qop = Protection.selectFrom(digest.params.get("qop"));

    // build response parameters
    String response = null;/*w w  w .j a va2s .c  o  m*/

    List<String> params = new LinkedList<>();
    params.add("username=" + quotedString(username));
    if (realm != null)
        params.add("realm=" + quotedString(realm));
    else
        return null;
    if (nonce != null)
        params.add("nonce=" + quotedString(nonce));
    else
        return null;
    if (opaque != null)
        params.add("opaque=" + quotedString(opaque));
    else
        return null;

    if (algorithm != null)
        params.add("algorithm=" + quotedString(algorithm.name));

    final String method = request.method();
    final String digestURI = request.httpUrl().encodedPath();
    params.add("uri=" + quotedString(digestURI));

    if (qop != null) {
        params.add("qop=" + qop.name);
        params.add("cnonce=" + quotedString(clientNonce));

        int nc = nonceCount.getAndIncrement();
        String ncValue = String.format("%08x", nc);
        params.add("nc=" + ncValue);

        String a1 = null;
        if (algorithm == Algorithm.MD5)
            a1 = username + ":" + realm + ":" + password;
        else if (algorithm == Algorithm.MD5_SESSION)
            a1 = h(username + ":" + realm + ":" + password) + ":" + nonce + ":" + clientNonce;
        //Constants.log.trace("A1=" + a1);

        String a2 = null;
        if (qop == Protection.Auth)
            a2 = method + ":" + digestURI;
        else if (qop == Protection.AuthInt)
            try {
                RequestBody body = request.body();
                a2 = method + ":" + digestURI + ":" + (body != null ? h(body) : h(""));
            } catch (IOException e) {
                Constants.log.warn("Couldn't get entity-body for hash calculation");
            }
        //Constants.log.trace("A2=" + a2);

        if (a1 != null && a2 != null)
            response = kd(h(a1), nonce + ":" + ncValue + ":" + clientNonce + ":" + qop.name + ":" + h(a2));

    } else {
        //Constants.log.debug("Using legacy Digest auth");

        // legacy (backwards compatibility with RFC 2069)
        if (algorithm == Algorithm.MD5) {
            String a1 = username + ":" + realm + ":" + password, a2 = method + ":" + digestURI;
            response = kd(h(a1), nonce + ":" + h(a2));
        }
    }

    if (response != null) {
        params.add("response=" + quotedString(response));
        return request.newBuilder().header(HEADER_AUTHORIZATION, "Digest " + TextUtils.join(", ", params))
                .build();
    } else
        return null;
}

From source file:au.com.wallaceit.reddinator.RedditData.java

License:Open Source License

private boolean createHttpClient() {
    httpClient = new OkHttpClient();
    httpClient.setConnectTimeout(10, TimeUnit.SECONDS);
    httpClient.setReadTimeout(10, TimeUnit.SECONDS);
    httpClient.networkInterceptors().add(new Interceptor() {
        @Override//from   w w w .  ja v  a 2  s.c  o  m
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request requestWithUserAgent = originalRequest.newBuilder().removeHeader("User-Agent")
                    .addHeader("User-Agent", userAgent).build();
            return chain.proceed(requestWithUserAgent);
        }
    });

    return true;
}

From source file:bitrefill.retrofit.Generator.java

static void configAuth(OkHttpClient client, Config config) {
    final String auth = getAuth(config);
    if (auth == null) {
        return;//w ww . ja v a  2  s  .c o  m
    }
    client.interceptors().clear();
    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();

            Request.Builder requestBuilder = original.newBuilder().header("Authorization", "Basic " + auth)
                    .header("Accept", "applicaton/json").method(original.method(), original.body());

            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });

}

From source file:butter.droid.base.providers.media.VodoProvider.java

License:Open Source License

@Override
protected Call enqueue(Request request, com.squareup.okhttp.Callback requestCallback) {
    Context context = ButterApplication.getAppContext();
    PackageInfo pInfo;/*  w w  w. jav a  2  s.com*/
    String versionName = "0.0.0";
    try {
        pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        versionName = pInfo.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    request = request.newBuilder().removeHeader("User-Agent").addHeader("User-Agent", String.format(
            "Mozilla/5.0 (Linux; U; Android %s; %s; %s Build/%s) AppleWebkit/534.30 (KHTML, like Gecko) PT/%s",
            Build.VERSION.RELEASE, LocaleUtils.getCurrentAsString(), Build.MODEL, Build.DISPLAY, versionName))
            .build();
    return super.enqueue(request, requestCallback);
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

private void rewriteRequestToServer(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse());

    interceptors.add(new Interceptor() {
        @Override//from w  w  w.j a  v a2s  . c om
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            return chain.proceed(originalRequest.newBuilder().method("POST", uppercase(originalRequest.body()))
                    .addHeader("OkHttp-Intercepted", "yep").build());
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).addHeader("Original-Header", "foo")
            .method("PUT", RequestBody.create(MediaType.parse("text/plain"), "abc")).build();

    FiberOkHttpUtil.executeInFiber(client, request);

    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("ABC", recordedRequest.getBody().readUtf8());
    assertEquals("foo", recordedRequest.getHeader("Original-Header"));
    assertEquals("yep", recordedRequest.getHeader("OkHttp-Intercepted"));
    assertEquals("POST", recordedRequest.getMethod());
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

private void multipleInterceptors(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse());

    interceptors.add(new Interceptor() {
        @Override/* www.  j a  v  a2s  . c  om*/
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Response originalResponse = chain
                    .proceed(originalRequest.newBuilder().addHeader("Request-Interceptor", "Android") // 1. Added first.
                            .build());
            return originalResponse.newBuilder().addHeader("Response-Interceptor", "Donut") // 4. Added last.
                    .build();
        }
    });
    interceptors.add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Response originalResponse = chain
                    .proceed(originalRequest.newBuilder().addHeader("Request-Interceptor", "Bob") // 2. Added second.
                            .build());
            return originalResponse.newBuilder().addHeader("Response-Interceptor", "Cupcake") // 3. Added third.
                    .build();
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();

    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertEquals(Arrays.asList("Cupcake", "Donut"), response.headers("Response-Interceptor"));

    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals(Arrays.asList("Android", "Bob"), recordedRequest.getHeaders().values("Request-Interceptor"));
}

From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java

License:Apache License

@Test
public void networkInterceptorsCanChangeRequestMethodFromGetToPost() throws Exception {
    server.enqueue(new MockResponse());

    client.networkInterceptors().add(new Interceptor() {
        @Override/*w w  w. ja  v  a 2s  .  co m*/
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            MediaType mediaType = MediaType.parse("text/plain");
            RequestBody body = RequestBody.create(mediaType, "abc");
            return chain.proceed(originalRequest.newBuilder().method("POST", body)
                    .header("Content-Type", mediaType.toString())
                    .header("Content-Length", Long.toString(body.contentLength())).build());
        }
    });

    Request request = new Request.Builder().url(server.url("/")).get().build();

    client.newCall(request).execute();

    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("POST", recordedRequest.getMethod());
    assertEquals("abc", recordedRequest.getBody().readUtf8());
}

From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java

License:Apache License

private void rewriteRequestToServer(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse());

    interceptors.add(new Interceptor() {
        @Override/*from w  w w  .ja  v  a  2  s.  c  om*/
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            return chain.proceed(originalRequest.newBuilder().method("POST", uppercase(originalRequest.body()))
                    .addHeader("OkHttp-Intercepted", "yep").build());
        }
    });

    Request request = new Request.Builder().url(server.url("/")).addHeader("Original-Header", "foo")
            .method("PUT", RequestBody.create(MediaType.parse("text/plain"), "abc")).build();

    client.newCall(request).execute();

    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("ABC", recordedRequest.getBody().readUtf8());
    assertEquals("foo", recordedRequest.getHeader("Original-Header"));
    assertEquals("yep", recordedRequest.getHeader("OkHttp-Intercepted"));
    assertEquals("POST", recordedRequest.getMethod());
}

From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java

License:Apache License

private void multipleInterceptors(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse());

    interceptors.add(new Interceptor() {
        @Override/*from w w w. ja va2 s.com*/
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Response originalResponse = chain
                    .proceed(originalRequest.newBuilder().addHeader("Request-Interceptor", "Android") // 1. Added first.
                            .build());
            return originalResponse.newBuilder().addHeader("Response-Interceptor", "Donut") // 4. Added last.
                    .build();
        }
    });
    interceptors.add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Response originalResponse = chain
                    .proceed(originalRequest.newBuilder().addHeader("Request-Interceptor", "Bob") // 2. Added second.
                            .build());
            return originalResponse.newBuilder().addHeader("Response-Interceptor", "Cupcake") // 3. Added third.
                    .build();
        }
    });

    Request request = new Request.Builder().url(server.url("/")).build();

    Response response = client.newCall(request).execute();
    assertEquals(Arrays.asList("Cupcake", "Donut"), response.headers("Response-Interceptor"));

    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals(Arrays.asList("Android", "Bob"), recordedRequest.getHeaders().values("Request-Interceptor"));
}