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:com.abiquo.apiclient.auth.BasicAuthentication.java

License:Apache License

@Override
public Request authenticate(final Request unauthenticated) {
    return unauthenticated.newBuilder().addHeader(HttpHeaders.AUTHORIZATION, authHeader).build();
}

From source file:com.apothesource.pillfill.network.PFNetworkManager.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Request requestWithApiKey = request.newBuilder().addHeader("api_key", apiKey).build();
    return chain.proceed(requestWithApiKey);
}

From source file:com.ayuget.redface.network.UserAgentInterceptor.java

License:Apache License

@Override
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);
}

From source file:com.brq.wallet.external.glidera.api.GlideraService.java

private GlideraService(@NonNull final NetworkParameters networkParameters) {
    Preconditions.checkNotNull(networkParameters);

    this.networkParameters = networkParameters;
    this.baseUrl = getBaseUrl(networkParameters);

    if (networkParameters.isTestnet()) {
        clientId = TESTNET_CLIENT_ID;//from  ww w  .jav  a 2s  . c  om
    } else {
        clientId = MAINNET_CLIENT_ID;
    }

    /**
     * The Sha256 HMAC hash of the message. Use the secret matching the access_key to hash the message.
     * The message is the concatenation of the X-ACCESS-NONCE + URI of the request + message body JSON.
     * The final X-ACCESS-SIGNATURE is the HmacSha256 of the UTF-8 encoding of the message as a Hex encoded string
     */
    final Interceptor apiCredentialInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            if (_oAuth1Response != null) {
                Request.Builder requestBuilder = request.newBuilder();

                synchronized (_nonce) {
                    final String nonce = _nonce.getNonceString();
                    final String uri = request.urlString();

                    String message = nonce + uri;

                    if (request.body() != null && request.body().contentLength() > 0) {
                        Buffer bodyBuffer = new Buffer();
                        request.body().writeTo(bodyBuffer);
                        byte[] bodyBytes = bodyBuffer.readByteArray();

                        String body = new String(bodyBytes, Charsets.UTF_8);
                        message += body;
                    }

                    final byte[] messageBytes = message.getBytes(Charsets.UTF_8);
                    final byte[] secretBytes = _oAuth1Response.getSecret().getBytes(Charsets.UTF_8);
                    final byte[] signatureBytes = Hmac.hmacSha256(secretBytes, messageBytes);

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    Hex.encode(signatureBytes, stream);
                    final String signature = stream.toString();

                    request = requestBuilder.header(HEADER_ACCESS_KEY, _oAuth1Response.getAccess_key())
                            .header(HEADER_ACCESS_NONCE, nonce).header(HEADER_ACCESS_SIGNATURE, signature)
                            .build();

                }
            }

            return chain.proceed(request);
        }
    };

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(15000, TimeUnit.MILLISECONDS);
    client.setReadTimeout(15000, TimeUnit.MILLISECONDS);
    client.networkInterceptors().add(apiCredentialInterceptor);

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    //objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.);
    objectMapper.registerModule(new WapiJsonModule());

    /*
    We should always add client_id to the header
     */
    RequestInterceptor requestInterceptor = new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade requestFacade) {
            requestFacade.addHeader(HEADER_CLIENT_ID, clientId);
        }
    };

    /*
    Create the json adapter
     */
    RestAdapter adapter = new RestAdapter.Builder().setEndpoint(baseUrl + "/api/" + API_VERSION + "/")
            //.setLogLevel(RestAdapter.LogLevel.FULL)
            .setLogLevel(RestAdapter.LogLevel.BASIC).setLog(new AndroidLog("Glidera"))
            .setConverter(new JacksonConverter(objectMapper)).setClient(new NullBodyAwareOkClient(client))
            .setRequestInterceptor(requestInterceptor).build();

    glideraApi = adapter.create(GlideraApi.class);
}

From source file:com.davidecirillo.dashboard.data.RestService.java

License:Apache License

public void create() {
    final OkHttpClient client = new OkHttpClient();

    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();

    if (BuildConfig.DEBUG)
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    else//from w  ww.j  a  v  a2 s  . c  o m
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);

    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.add(loggingInterceptor);
    interceptors.add(new LoggingInterceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            Request request = original.newBuilder().method(original.method(), original.body()).build();

            return chain.proceed(request);
        }
    });

    client.networkInterceptors().addAll(interceptors);

    retrofit.Retrofit restAdapterLocal = new retrofit.Retrofit.Builder().client(client)
            .baseUrl(AppConfig.http + mLocalUrl).addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

    retrofit.Retrofit restAdapterRemote = new retrofit.Retrofit.Builder().client(client)
            .baseUrl(AppConfig.http + mRemoteUrl).addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

    mLocalPiApi = restAdapterLocal.create(PIApi.class);

    mRemotePiApi = restAdapterRemote.create(PIApi.class);
}

From source file:com.dreamdigitizers.androidsoundcloudapi.core.Api.java

private Api(final String pClientId, final String pOauthToken) {
    OkHttpClient okHttpClient = new OkHttpClient();

    okHttpClient.interceptors().add(new Interceptor() {
        @Override//from ww  w .j ava2  s. c om
        public Response intercept(Chain pChain) throws IOException {
            Request request = pChain.request();
            HttpUrl.Builder builder = request.httpUrl().newBuilder();
            builder.addQueryParameter("client_id", pClientId);
            if (!TextUtils.isEmpty(pOauthToken)) {
                builder.addQueryParameter("oauth_token", pOauthToken);
            }
            HttpUrl httpUrl = builder.build();
            Log.d(Api.TAG, httpUrl.url().toString());
            request = request.newBuilder().url(httpUrl).build();
            Response response = pChain.proceed(request);
            String bodyString = response.body().string();
            response = response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), bodyString)).build();
            Log.d(Api.TAG, bodyString);
            return response;
        }
    });

    Retrofit retrofit = new Retrofit.Builder().baseUrl(IApi.API_URL__BASE).client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

    this.mApi = retrofit.create(IApi.class);
}

From source file:com.example.data.net.interceptor.UserAgentInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    final Request originalRequest = chain.request();
    final Request requestWithUserAgent = originalRequest.newBuilder().removeHeader(USER_AGENT_HEADER_NAME)
            .addHeader(USER_AGENT_HEADER_NAME, userAgentHeaderValue).build();
    return chain.proceed(requestWithUserAgent);
}

From source file:com.github.kskelm.baringo.AuthService.java

License:Open Source License

protected Request buildAuthenticatedRequest(Request request) {
    if (oAuth2 != null && oAuth2.getAccessToken() != null) {
        request = request.newBuilder().header("Authorization", getAuthenticationHeader()).build();
    } else {//from  w ww  . j  a va2  s  . co  m
        request = request.newBuilder().header("Authorization", getAuthenticationHeader()).build();
    } // if-else
    return request;
}

From source file:com.heroiclabs.sdk.android.util.http.GzipRequestInterceptor.java

License:Apache License

/** {@inheritDoc} */
@Override//from w  ww .  jav  a 2 s  . c  o  m
public Response intercept(final Chain chain) throws IOException {
    final Request originalRequest = chain.request();

    // Do not compress requests already encoded, or that are too small.
    if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null
            || originalRequest.body().contentLength() < 300) {
        return chain.proceed(originalRequest);
    }

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

From source file:com.hexdo.hexexamples.network.GOERetrofit.java

License:Open Source License

public static <S> S createService(Class<S> serviceClass, final String authToken) {
    List<Interceptor> interceptors = httpClient.interceptors();
    interceptors.clear();/*from w  w w.  ja v  a 2  s .c  om*/
    if (authToken != null) {
        interceptors.add(new Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                Request original = chain.request();

                // Request customization: add request headers
                Request.Builder requestBuilder = original.newBuilder().header("Authorization", authToken)
                        .method(original.method(), original.body());

                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });
    }
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    // set your desired log level
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    interceptors.add(logging);

    Retrofit retrofit = builder.client(httpClient).build();
    return retrofit.create(serviceClass);
}