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.shahul3d.indiasatelliteweather.service.DownloaderService.java

License:Open Source License

void initializeHTTPClient() {
    httpClient = new OkHttpClient();
    try {/*w w  w.  ja v a  2  s .  c o  m*/
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache responseCache = new Cache(getApplicationContext().getCacheDir(), cacheSize);
        httpClient.setCache(responseCache);
    } catch (Exception e) {
        trackException("Can't set HTTP cache", e);
    }
    httpClient.setReadTimeout(90, TimeUnit.SECONDS);
    httpClient.setConnectTimeout(30, TimeUnit.SECONDS);
}

From source file:com.shalzz.attendance.wrapper.MyOkHttpStack.java

License:Open Source License

public MyOkHttpStack() {
    this(new OkUrlFactory(new OkHttpClient()));
}

From source file:com.shazam.minishazam.service.ShazamServiceApiBase.java

License:Apache License

private static RestAdapter.Builder getApiBuilder() {

    /* Client used to interface with the REST API. It builds upon the base url */
    return new RestAdapter.Builder()
            /* Logging */
            .setLogLevel(RestAdapter.LogLevel.FULL)
            /* Set the BASE URL for Shazam as the endpoint as interfaces will refer only to relative paths */
            .setEndpoint(BASE_URL)
            /* Use OkHttp Client for better performance */
            .setClient(new OkClient(new OkHttpClient()));
}

From source file:com.shipdream.lib.android.mvc.samples.note.service.http.internal.WeatherServiceImpl.java

License:Apache License

public WeatherServiceImpl() {
    httpClient = new OkHttpClient();
    gson = new Gson();
}

From source file:com.shopify.buy.dataprovider.BuyClientFactory.java

License:Open Source License

/**
 * Returns a BuyClient initialized with the given shop domain and API key.
 * After you have <a href="https://docs.shopify.com/api/mobile-buy-sdk/adding-mobile-app-sales-channel">added the mobile sales channel to your store</a>,
 * you can find the API Key and Channel ID in your store admin page. Click on Mobile App and then click on Integration.
 *
 * @param shopDomain      the domain of the shop to checkout with, in the format 'shopname.myshopify.com'
 * @param apiKey          a valid Shopify API key
 * @param channelId       a valid Shopify Channel ID
 * @param applicationName the name to attribute orders to. The value for {@code applicationName} should be the application package name, as used to publish your application on the Play Store.  This is usually the value returned by {@link Activity#getPackageName()}, or BuildConfig.APPLICATION_ID if you are using gradle.
 * @return a {@link BuyClient}/*from  w ww.  j a va2  s. co  m*/
 */
public static BuyClient getBuyClient(final String shopDomain, final String apiKey, final String channelId,
        final String applicationName) throws IllegalArgumentException {
    if (TextUtils.isEmpty(shopDomain) || shopDomain.contains(":") || shopDomain.contains("/")
            || !shopDomain.contains(".myshopify.com")) {
        throw new IllegalArgumentException(
                "shopDomain must be of the form 'shopname.myshopify.com' and cannot start with 'http://'");
    }

    if (TextUtils.isEmpty(apiKey)) {
        throw new IllegalArgumentException("apiKey must be provided, and cannot be empty");
    }

    if (TextUtils.isEmpty(channelId)) {
        throw new IllegalArgumentException("channelId must be provided, and cannot be empty");
    }

    if (TextUtils.isEmpty(applicationName)) {
        throw new IllegalArgumentException("applicationName must be provided, and cannot be empty");
    }

    RequestInterceptor requestInterceptor = new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade request) {
            request.addHeader("Authorization",
                    "Basic " + Base64.encodeToString(apiKey.getBytes(), Base64.NO_WRAP));

            // Using the full package name for BuildConfig here as a work around for Javadoc.  The source paths need to be adjusted
            request.addHeader("User-Agent", "Mobile Buy SDK Android/" + com.shopify.buy.BuildConfig.VERSION_NAME
                    + "/" + applicationName);
        }
    };

    OkHttpClient httpClient = new OkHttpClient();

    RestAdapter adapter = new RestAdapter.Builder().setEndpoint("https://" + shopDomain)
            .setConverter(new GsonConverter(createDefaultGson())).setClient(new OkClient(httpClient))
            .setLogLevel(BuildConfig.RETROFIT_LOG_LEVEL).setRequestInterceptor(requestInterceptor).build();

    return new BuyClient(adapter.create(BuyRetrofitService.class), apiKey, channelId, applicationName,
            shopDomain, httpClient);
}

From source file:com.simonmacdonald.muzei.comic.ComicCoverArtSource.java

License:Open Source License

private boolean isValidImage(String imageUrl) throws RetryException {
    OkHttpClient client = new OkHttpClient();
    try {/*from w  w w  . j  a  va 2 s  .c om*/
        URL url = new URL(imageUrl);
        HttpURLConnection connection = client.open(url);
        String type = connection.getContentType();
        //           Log.d(TAG, "Content-Type = " + type);
        return type.startsWith("image");
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return false;
}

From source file:com.simonmacdonald.muzei.comic.ComicCoverArtSource.java

License:Open Source License

private JsonObject makeComicVineApiRequest(String strUrl) {
    OkHttpClient client = new OkHttpClient();
    URL url;/*from  w w  w . j  a v  a2s . c o m*/
    String json = "";
    try {
        url = new URL(strUrl);
        HttpURLConnection connection = client.open(url);
        InputStream in = null;
        try {
            // Read the response.
            in = connection.getInputStream();
            byte[] response = readFully(in);
            json = new String(response, "UTF-8");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Gson gson = new Gson();
    return gson.fromJson(json, JsonObject.class);
}

From source file:com.somexapps.wyre.services.ServiceGenerator.java

License:Apache License

public static <S> S createService(Class<S> serviceClass, String baseUrl, String username, String password) {
    // Create builder for rest adapter with baseUrl and client
    RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint(baseUrl)
            .setClient(new OkClient(new OkHttpClient()));

    // Check if username and password were passed
    if (username != null && password != null) {
        final String credentials = username + ":" + password;

        builder.setRequestInterceptor(new RequestInterceptor() {
            @Override/*from ww  w  .j av  a 2 s . c  o  m*/
            public void intercept(RequestFacade request) {
                String encoded = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

                request.addHeader("Accept", "application/json");
                request.addHeader("Authorization", encoded);
            }
        });
    }

    // Create adapter from builder
    RestAdapter adapter = builder.build();

    // Create new adapter with the passed class as the interface.
    return adapter.create(serviceClass);
}

From source file:com.somexapps.wyre.services.ServiceGenerator.java

License:Apache License

public static <S> S createService(Class<S> serviceClass, String baseUrl, final AccessTokenResult accessToken) {
    // Create builder for rest adapter with baseUrl and client
    RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint(baseUrl)
            .setClient(new OkClient(new OkHttpClient()));

    // Check if username and password were passed
    if (accessToken != null) {
        builder.setRequestInterceptor(new RequestInterceptor() {
            @Override/*  w ww .  j av  a2  s .  com*/
            public void intercept(RequestFacade request) {
                request.addHeader("Accept", "application/json");
                request.addHeader("Authorization", accessToken.getScope() + " " + accessToken.getAccessToken());
            }
        });
    }

    // Create adapter from builder
    RestAdapter adapter = builder.build();

    // Create new adapter with the passed class as the interface.
    return adapter.create(serviceClass);
}

From source file:com.sonaive.v2ex.sync.api.Api.java

License:Open Source License

public Bundle sync(HttpMethod httpMethod) {
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = null;/*w  w  w  .jav  a2 s.com*/

    if (httpMethod == HttpMethod.GET) {
        request = new Request.Builder().url(mUrl).build();
    } else {
        String json = mArguments.getString(ARG_API_PARAMS);
        HashMap params = new Gson().fromJson(json, HashMap.class);
        FormEncodingBuilder formBodyBuilder = new FormEncodingBuilder();
        for (Map.Entry<String, String> entry : ((HashMap<String, String>) params).entrySet()) {
            formBodyBuilder.add(entry.getKey(), entry.getValue());
        }
        RequestBody formBody = formBodyBuilder.build();
        request = new Request.Builder().url(mUrl).post(formBody).build();
    }

    try {
        Response response = okHttpClient.newCall(request).execute();
        if (response != null && response.code() == 200) {
            LOGD(TAG, "Request: " + mUrl + ", server returned HTTP_OK, so fetching was successful.");
            mArguments.putString(Api.ARG_RESULT, response.body().string());
            return mArguments;
        } else if (response != null && response.code() == 403) {
            LOGW(TAG, "Request: " + mUrl + ", Server returned 403, fetching was failed.");
        } else {
            LOGW(TAG, "Request: " + mUrl + ", Fetching was failed. Unknown reason");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}