Example usage for com.squareup.okhttp OkHttpClient OkHttpClient

List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient

Introduction

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

Prototype

public OkHttpClient() 

Source Link

Usage

From source file:com.battlelancer.seriesguide.util.LocalOnlyOkHttpDownloader.java

License:Apache License

private LocalOnlyOkHttpDownloader(final Context context, final File cacheDir, final long maxSize) {
    this.context = context.getApplicationContext();
    this.urlFactory = new OkUrlFactory(new OkHttpClient());
    try {/*from w w  w  .  j  a  v a2 s  .com*/
        urlFactory.client().setCache(new com.squareup.okhttp.Cache(cacheDir, maxSize));
    } catch (IOException ignored) {
    }
}

From source file:com.battlelancer.seriesguide.util.ServiceUtils.java

License:Apache License

/**
 * Returns this apps {@link com.squareup.okhttp.OkHttpClient} with enabled response cache.
 * Should be used with API calls.//  w w w  .  j av  a 2 s .c  om
 */
@NonNull
public static synchronized OkHttpClient getCachingOkHttpClient(Context context) {
    if (cachingHttpClient == null) {
        cachingHttpClient = new OkHttpClient();
        cachingHttpClient.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        cachingHttpClient.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        File cacheDir = createApiCacheDir(context);
        cachingHttpClient.setCache(new Cache(cacheDir, calculateApiDiskCacheSize(cacheDir)));
    }
    return cachingHttpClient;
}

From source file:com.belatrixsf.allstars.utils.di.modules.RetrofitModule.java

License:Open Source License

@Singleton
@Provides//from   w ww .  j av  a 2  s  . c o  m
public Retrofit provideRetrofit() {
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(loggingInterceptor);
    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            String token = PreferencesManager.get().getToken();
            if (token != null) {
                Request request = chain.request().newBuilder().addHeader("Authorization", "Token " + token)
                        .build();
                return chain.proceed(request);
            }
            return chain.proceed(chain.request());
        }
    });
    return new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BuildConfig.BASE_URL).client(client).build();
}

From source file:com.bitants.wally.base.WallyApplication.java

License:Apache License

@Override
public void onCreate() {
    super.onCreate();
    Glide.get(this).register(GlideUrl.class, InputStream.class,
            new OkHttpUrlLoader.Factory(new OkHttpClient()));
    applicationContext = getApplicationContext();
    startCrashLoggingIfUserAccepted();/*from w w w  . j a  v a 2s . c om*/
    checkVersionInstalled(BuildConfig.VERSION_CODE);
}

From source file:com.braisgabin.fbstats.Api.java

License:Apache License

public Api(String accessToken) {
    this.accessToken = accessToken;

    this.client = new OkHttpClient();

    this.mapper = new ObjectMapper();
    this.mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
    this.mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE);
    this.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    this.mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true);
}

From source file:com.brq.wallet.bitid.BitIdAuthenticator.java

License:Microsoft Reference Source License

private OkHttpClient getOkHttpClient() {
    OkHttpClient client = new OkHttpClient();
    if (!enforceSslCorrectness) {
        //user explicitly agreed to not check certificates
        client.setSslSocketFactory(SslUtils.SSL_SOCKET_FACTORY_ACCEPT_ALL);
        client.setHostnameVerifier(SslUtils.HOST_NAME_VERIFIER_ACCEPT_ALL);
    }//w ww  .ja  va  2  s  .  c o  m
    client.setConnectTimeout(Constants.SHORT_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(Constants.SHORT_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    return client;
}

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 w ww  .j a v a  2s  .  c o m
    } 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.btkelly.gnag.api.GitHubApi.java

License:Apache License

private GitHubApi(final GnagPluginExtension gnagPluginExtension) {
    this.gnagPluginExtension = gnagPluginExtension;

    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.interceptors().add(new AuthInterceptor(gnagPluginExtension));
    okHttpClient.interceptors().add(new LoggingInterceptor());

    String baseUrl = "https://api.github.com/repos/" + gnagPluginExtension.getGitHubRepoName() + "/";

    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

    GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson);

    Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl).client(okHttpClient)
            .addConverterFactory(gsonConverterFactory).build();

    gitHubApiClient = retrofit.create(GitHubApiClient.class);
}

From source file:com.bugsbunnybr.benchmarks.uil.OkHttpImageDownloader.java

License:Apache License

protected HttpURLConnection createConnection(String url, Object extra) throws IOException {

    String encodedUrl = Uri.encode(url, ALLOWED_URI_CHARS);

    OkHttpClient client = new OkHttpClient();

    HttpURLConnection conn = client.open(new URL(encodedUrl));
    conn.setConnectTimeout(connectTimeout);
    conn.setReadTimeout(readTimeout);/* www. j av  a 2 s .co m*/
    return conn;
}

From source file:com.bugsbunnybr.benchmarks.volley.OkHttpStack.java

License:Apache License

public OkHttpStack() {
    this(new OkHttpClient());
}