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:io.fabric8.openshift.client.internal.OpenShiftOAuthInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    //Build new request
    Request.Builder builder = request.newBuilder();
    builder.header("Accept", "application/json");

    String token = oauthToken.get();
    if (Utils.isNotNullOrEmpty(token)) {
        setAuthHeader(builder, token);//  w ww .jav  a 2s  .c om
    }

    request = builder.build();
    Response response = chain.proceed(request);

    if ((response.code() == 401 || response.code() == 403) && Utils.isNotNullOrEmpty(config.getUsername())
            && Utils.isNotNullOrEmpty(config.getPassword())) {
        // Close the previous response to prevent leaked connections.
        response.body().close();

        synchronized (client) {
            token = authorize();
            if (token != null) {
                oauthToken.set(token);
                setAuthHeader(builder, token);
                request = builder.build();
                return chain.proceed(request); //repeat request with new token
            }
        }
    }
    return response;
}

From source file:io.jawg.osmcontributor.rest.utils.AuthenticationRequestInterceptor.java

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
    Map<String, String> oAuthParams = loginPreferences.retrieveOAuthParams();

    if (oAuthParams != null) {
        Request originalRequest = response.request();
        String requestUrl = originalRequest.urlString();

        OAuthRequest oAuthRequest = new OAuthRequest(oAuthParams.get(CONSUMER_PARAM),
                oAuthParams.get(CONSUMER_SECRET_PARAM));
        oAuthRequest/*from   w  w w  .  j  ava2 s.  c om*/
                .initParam(OAuthParams.getOAuthParams().put(TOKEN_PARAM, oAuthParams.get(TOKEN_PARAM)).toMap());
        oAuthRequest.setOAuthToken(oAuthParams.get(TOKEN_PARAM));
        oAuthRequest.setOAuthTokenSecret(oAuthParams.get(TOKEN_SECRET_PARAM));
        oAuthRequest.setRequestUrl(requestUrl);
        oAuthRequest.signRequest(Verb.valueOf(originalRequest.method()));
        oAuthRequest.encodeParams();

        Request.Builder finalRequest = originalRequest.newBuilder().header("Accept", "text/xml")
                .header("Authorization", oAuthRequest.getOAuthHeader())
                .method(originalRequest.method(), originalRequest.body());
        return finalRequest.build();
    } else {
        // create Base64 encoded string
        String authorization = "Basic " + Base64.encodeToString(
                (loginPreferences.retrieveLogin() + ":" + loginPreferences.retrievePassword()).getBytes(),
                Base64.NO_WRAP);
        return response.request().newBuilder().header("Authorization", authorization)
                .header("Accept", "text/xml").build();
    }
}

From source file:io.minio.RequestSigner.java

License:Apache License

private Request signV4(Request originalRequest, byte[] data)
        throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, IOException {
    if (this.accessKey == null || this.secretKey == null) {
        return originalRequest;
    }//from  ww w . j  a  va  2s . c o  m

    String region = getRegion(originalRequest);
    byte[] dataHashBytes = computeSha256(data);
    String dataHash = DatatypeConverter.printHexBinary(dataHashBytes).toLowerCase();

    String host = originalRequest.uri().getHost();
    int port = originalRequest.uri().getPort();
    if (port != -1) {
        String scheme = originalRequest.uri().getScheme();
        if ("http".equals(scheme) && port != 80) {
            host += ":" + originalRequest.uri().getPort();
        } else if ("https".equals(scheme) && port != 443) {
            host += ":" + originalRequest.uri().getPort();
        }
    }

    Request signedRequest = originalRequest.newBuilder().header("x-amz-content-sha256", dataHash)
            .header("Host", host).build();

    // get signed headers
    String signedHeaders = getSignedHeaders(signedRequest);

    // get canonical request and headers to sign
    String canonicalRequest = getCanonicalRequest(signedRequest, dataHash, signedHeaders);

    // get sha256 of canonical request
    byte[] canonicalHashBytes = computeSha256(canonicalRequest.getBytes("UTF-8"));
    String canonicalHash = DatatypeConverter.printHexBinary(canonicalHashBytes).toLowerCase();

    // get key to sign
    String stringToSign = getStringToSign(region, canonicalHash, this.date);
    byte[] signingKey = getSigningKey(this.date, region, this.secretKey);

    // get signing key
    String signature = DatatypeConverter.printHexBinary(getSignature(signingKey, stringToSign)).toLowerCase();

    // get authorization header
    String authorization = getAuthorizationHeader(signedHeaders, signature, this.date, region);

    signedRequest = signedRequest.newBuilder().header("Authorization", authorization).build();

    return signedRequest;
}

From source file:io.minio.Signer.java

License:Apache License

/**
 * Returns signed request object for given request, region, access key and secret key.
 *//* www  .ja v a2  s  . c o  m*/
public static Request signV4(Request request, String region, String accessKey, String secretKey)
        throws NoSuchAlgorithmException, InvalidKeyException {
    String contentSha256 = request.header("x-amz-content-sha256");
    DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date"));

    Signer signer = new Signer(request, contentSha256, date, region, accessKey, secretKey);
    signer.setScope();
    signer.setCanonicalRequest();
    signer.setStringToSign();
    signer.setSigningKey();
    signer.setSignature();
    signer.setAuthorization();

    return request.newBuilder().header("Authorization", signer.authorization).build();
}

From source file:it.smartcommunitylab.GzipRequestInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request originalRequest = chain.request();
    if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
        return chain.proceed(originalRequest);
    }/*from w w  w.ja v  a  2 s .  c om*/

    Request compressedRequest = originalRequest.newBuilder().header("Content-Encoding", "gzip")
            .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))).build();
    return chain.proceed(compressedRequest);
}

From source file:me.touko.okhttp2.util.RequestBodyUtil.java

License:Apache License

public static byte[] readBody(Request request) throws IOException {
    if (!hasRequestBody(request)) {
        return new byte[0];
    } else {/*from   w w  w  .j  a v a  2  s. c om*/
        final Request copy = request.newBuilder().build();
        final Buffer buffer = new Buffer();
        copy.body().writeTo(buffer);
        return buffer.readByteArray();
    }
}

From source file:net.uiqui.oblivion.client.rest.RetryHandler.java

License:Apache License

public Response intercept(final Chain chain) throws IOException {
    final Request request = chain.request();

    try {/*from   ww  w .  j  a  v  a 2  s . c om*/
        return chain.proceed(request);
    } catch (SocketTimeoutException e) {
        cluster.nextServer();

        final Server server = cluster.server();
        final URL url = URLBuilder.change(request.url(), server.getServer(), server.getPort());
        final Request retry = request.newBuilder().url(url).build();

        return chain.proceed(retry);
    }
}

From source file:org.dataconservancy.cos.osf.client.support.AuthInterceptor.java

License:Apache License

@Override
public Response intercept(final Chain chain) throws IOException {

    String localAuthheader = null;

    // Check the value of the authHeader field, which may have been set on construction
    if (authHeader != null && !authHeader.trim().equals("")) {
        localAuthheader = authHeader;//  w  w w  . ja  v a 2s  .  c  om
    }

    // If it wasn't set, see if there's a configuration service and use that
    if (osfConfigurationService != null && osfConfigurationService.getConfiguration().getAuthHeader() != null
            && !osfConfigurationService.getConfiguration().getAuthHeader().trim().equals("")) {
        localAuthheader = osfConfigurationService.getConfiguration().getAuthHeader();
    }

    // if the auth header has been set, use it, otherwise simply proceed with the chain.
    if (localAuthheader == null) {
        return chain.proceed(chain.request());
    }

    Request req = chain.request();

    if (req.header("Authorization") == null) {
        req = req.newBuilder().addHeader("Authorization", localAuthheader).build();
    }

    return chain.proceed(req);
}

From source file:org.fs.ghanaian.soap.SoapObjectCallback.java

License:Apache License

/***
 *
 * @param request/*from   w  w w  .j  av a2 s  .c o  m*/
 * @return
 */
@Override
public CoreCallback<Document> addRequest(Request request) {
    if (request != null) {
        Serializer serializer = new Serializer();
        RequestBody body = RequestBody.create(MediaType.parse("text/xml; charset=utf-8"),
                serializer.serialize(envelope));
        Request newRequest = request.newBuilder().post(body).build();
        mRequest = newRequest;
    }
    return this;
}

From source file:org.graylog2.rest.RemoteInterfaceProvider.java

License:Open Source License

public <T> T get(Node node, final String authorizationToken, Class<T> interfaceClass) {
    final OkHttpClient okHttpClient = this.okHttpClient.clone();
    okHttpClient.interceptors().add(new Interceptor() {
        @Override//from   w  ww  .  ja  va2 s .  c  o  m
        public Response intercept(Interceptor.Chain chain) throws IOException {
            final Request original = chain.request();

            Request.Builder builder = original.newBuilder().header("Accept", "application/json")
                    .method(original.method(), original.body());

            if (authorizationToken != null) {
                builder = builder.header("Authorization", authorizationToken);
            }

            return chain.proceed(builder.build());
        }
    });
    final Retrofit retrofit = new Retrofit.Builder().baseUrl(node.getTransportAddress())
            .addConverterFactory(JacksonConverterFactory.create(objectMapper)).client(okHttpClient).build();

    return retrofit.create(interfaceClass);
}