Java Examples for com.squareup.okhttp.OkHttpClient

The following java examples will help you to understand the usage of com.squareup.okhttp.OkHttpClient. These source code samples are taken from different open source projects.

Example 1
Project: CrossBow-master  File: HttpStackSelector.java View source code
public static HttpStack createStack() {
    if (hasOkHttp()) {
        OkHttpClient okHttpClient = new OkHttpClient();
        VolleyLog.d("OkHttp found, using okhttp for http stack");
        return new OkHttpStack(okHttpClient);
    } else if (useHttpClient()) {
        VolleyLog.d("Android version is older than Gingerbread (API 9), using HttpClient");
        return new HttpClientStack(AndroidHttpClient.newInstance(USER_AGENT));
    } else {
        VolleyLog.d("Using Default HttpUrlConnection");
        return new HurlStack();
    }
}
Example 2
Project: AreYouAlive-master  File: ServiceGenerator.java View source code
public static <S> S createService(Class<S> serviceClass, Context context) {
    File cacheDirectory = new File(Environment.getExternalStorageDirectory(), "HttpCache");
    // 10 MiB
    int cacheSize = 10 * 1024 * 1024;
    OkHttpClient client = new OkHttpClient();
    Cache cache = null;
    try {
        cache = new Cache(cacheDirectory, cacheSize);
    } catch (IOException e) {
        e.printStackTrace();
    }
    client.setCache(cache);
    RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint("http://areyoualive.org/").setConverter(new LoganSquareConverter()).setClient(new OkClient(client)).setLogLevel(RestAdapter.LogLevel.FULL);
    RestAdapter adapter = builder.build();
    return adapter.create(serviceClass);
}
Example 3
Project: Hacker-News-Android-master  File: OkClientModule.java View source code
@Provides
@Named("okclient")
OkClient providesOkClient() {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setFollowRedirects(true);
    okHttpClient.setFollowSslRedirects(true);
    if (mInterceptorList != null) {
        okHttpClient.networkInterceptors().addAll(mInterceptorList);
    }
    okHttpClient.networkInterceptors().add(new StethoInterceptor());
    return new OkClient(okHttpClient);
}
Example 4
Project: MusicDNA-master  File: Net.java View source code
public static String getUrlAsString(URL paramURL) throws IOException {
    Request request = new Request.Builder().header("User-Agent", USER_AGENT).url(paramURL).build();
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, TimeUnit.SECONDS);
    Response response = client.newCall(request).execute();
    return response.body().string();
}
Example 5
Project: OAuth-Magento-Rest-Api-Retrofit-master  File: ServiceGenerator.java View source code
public static <S> S createService(Class<S> serviceClass, String baseUrl, final OAuthParameters oAuthParams) {
    OkHttpClient client = new OkHttpClient();
    client.networkInterceptors().add(new OAuthInterceptor(oAuthParams));
    builder.setClient(new OkClient(client));
    builder.setEndpoint(baseUrl).setLogLevel(RestAdapter.LogLevel.FULL);
    builder.setConverter(new SimpleXMLConverter());
    RestAdapter adapter = builder.build();
    return adapter.create(serviceClass);
}
Example 6
Project: RxAndroidBootstrap-master  File: BaseRetrofitClient.java View source code
public <T> T initRestAdapter(Context context, String endPoint, Class<T> restInterface) {
    okHttpClient = new OkHttpClient();
    okHttpClient.setCookieHandler(CookieHandler.getDefault());
    okHttpClient.setConnectTimeout(10, TimeUnit.MINUTES);
    connectivityAwareUrlClient = new ConnectivityAwareUrlClient(context, new OkClient(okHttpClient));
    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(endPoint).setClient(connectivityAwareUrlClient).build();
    return restAdapter.create(restInterface);
}
Example 7
Project: tuchong-daily-android-master  File: TuchongApplication.java View source code
public void setPicasso() {
    OkHttpClient client = new OkHttpClient();
    client.networkInterceptors().add(new StethoInterceptor());
    File cache = new File(this.getCacheDir(), PICASSO_CACHE);
    if (!cache.exists()) {
        //noinspection ResultOfMethodCallIgnored
        cache.mkdirs();
    }
    try {
        client.setCache(new Cache(cache, PICASSO_CACHE_SIZE));
    } catch (IOException e) {
        e.printStackTrace();
    }
    Picasso picasso = new Picasso.Builder(this).downloader(new OkHttpDownloader(client)).build();
    Picasso.setSingletonInstance(picasso);
}
Example 8
Project: marvel-api-master  File: RetrofitHttpClient.java View source code
private static OkUrlFactory generateDefaultOkUrlFactory() {
    OkHttpClient client = new com.squareup.okhttp.OkHttpClient();
    client.setConnectTimeout(CONNECT_TIMEOUT_SEC, TimeUnit.SECONDS);
    client.setReadTimeout(READ_TIMEOUT_SEC, TimeUnit.SECONDS);
    try {
        File cacheDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
        Cache cache = new Cache(cacheDir, 1024);
        client.setCache(cache);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new OkUrlFactory(client);
}
Example 9
Project: android-mvvm-example-master  File: OMDBApiFactory.java View source code
/**
     * Creates a fresh OMDBApiService instance with the given client.
     */
public static OMDBApiService newApi(OkHttpClient client) {
    // Gson
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(SearchResultsDeserializer.TYPE, new SearchResultsDeserializer());
    Gson gson = gsonBuilder.create();
    // Build API service
    return new Retrofit.Builder().client(client).baseUrl(API_ENDPOINT).addConverterFactory(GsonConverterFactory.create(gson)).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build().create(OMDBApiService.class);
}
Example 10
Project: AndroidTvBoilerplate-master  File: AndroidTvBoilerplateService.java View source code
public static AndroidTvBoilerplateService newVineyardService() {
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            // Catch unauthorised error
            return response;
        }
    });
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);
    Retrofit retrofit = new Retrofit.Builder().baseUrl(AndroidTvBoilerplateService.ENDPOINT).client(client).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
    return retrofit.create(AndroidTvBoilerplateService.class);
}
Example 11
Project: congress-android-master  File: HttpManager.java View source code
public static void init() {
    if (initialized)
        return;
    initialized = true;
    OkHttpClient okHttpClient = new OkHttpClient();
    // adapted from https://github.com/mapbox/mapbox-android-sdk/pull/244
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, null, null);
    } catch (GeneralSecurityException e) {
        throw new AssertionError();
    }
    okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
    Log.w(Utils.TAG, "Initializing an OkHttpClient instance as the URL stream handler factory forevermore.");
    URL.setURLStreamHandlerFactory(okHttpClient);
}
Example 12
Project: devcon-android-2014-master  File: DevConDebugApplication.java View source code
@Override
public void onCreate() {
    super.onCreate();
    okHttpClient = new OkHttpClient();
    LOGI(TAG, "on create from " + getClass().getCanonicalName());
    long startTime = SystemClock.elapsedRealtime();
    initializeStetho(this);
    long elapsed = SystemClock.elapsedRealtime() - startTime;
    LOGI(TAG, "Stetho initialized in " + elapsed + " ms");
}
Example 13
Project: DevConSummit-master  File: FakeAPITestModule.java View source code
@Provides
public RestAdapter provideRestAdapter(MockWebServer mockWebServer) {
    int SIZE_OF_CACHE = 1024;
    OkHttpClient ok = new OkHttpClient();
    ok.setReadTimeout(30, TimeUnit.SECONDS);
    ok.setConnectTimeout(30, TimeUnit.SECONDS);
    try {
        Cache responseCache = new Cache(DevConApplication.getInstance().getCacheDir(), SIZE_OF_CACHE);
        ok.setCache(responseCache);
    } catch (Exception e) {
        Log.d("OkHttp", "Unable to set http cache", e);
    }
    Executor executor = Executors.newCachedThreadPool();
    return new RestAdapter.Builder().setExecutors(executor, executor).setClient(new OkClient(ok)).setEndpoint(mockWebServer.getUrl("/").toString()).setRequestInterceptor(new ApiRequestInterceptor()).build();
}
Example 14
Project: LoopSeries-Mobile-master  File: LoopAnimeGlideModule.java View source code
@Override
public void registerComponents(Context context, Glide glide) {
    if (BuildConfig.DEBUG) {
        OkHttpClient client = new OkHttpClient();
        client.networkInterceptors().add(new StethoInterceptor());
        OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory(client);
        glide.register(GlideUrl.class, InputStream.class, factory);
    }
}
Example 15
Project: maepaysoh-android-master  File: RetrofitHelper.java View source code
public static RestAdapter getResAdapter(final String token) {
    if (BuildConfig.DEBUG) {
        return new RestAdapter.Builder().setClient(new OkClient(new OkHttpClient())).setEndpoint("http://api.maepaysoh.org").setLogLevel(RestAdapter.LogLevel.FULL).setRequestInterceptor(new RequestInterceptor() {

            @Override
            public void intercept(RequestFacade request) {
                request.addQueryParam("token", token);
            }
        }).build();
    } else {
        return new RestAdapter.Builder().setClient(new OkClient(new OkHttpClient())).setEndpoint("http://api.maepaysoh.org").setLogLevel(RestAdapter.LogLevel.NONE).setRequestInterceptor(new RequestInterceptor() {

            @Override
            public void intercept(RequestFacade request) {
                request.addQueryParam("token", token);
            }
        }).build();
    }
}
Example 16
Project: MD-BiliBili-master  File: TopicApi.java View source code
@Override
public void call(Subscriber<? super Topic> subscriber) {
    Request request = new Request.Builder().url("http://www.bilibili.com/index/slideshow.json").build();
    try {
        Response response = new OkHttpClient().newCall(request).execute();
        if (response.isSuccessful()) {
            Topic topic = new Gson().fromJson(response.body().string(), Topic.class);
            subscriber.onNext(topic);
        } else {
            subscriber.onError(new Exception(response.message()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 17
Project: Mover-master  File: FetchAvailableVideoQualities.java View source code
@Override
public Mover.Suggestion doBackgroundJob() {
    OkHttpClient client = new OkHttpClient();
    final int length = mQualities.size();
    for (int i = 0; i < length; i++) {
        if (checkQuality(mId, mQualities.get(0), client)) {
            break;
        }
        mQualities.remove(0);
    }
    return new Mover.Suggestion(mQualities, mId);
}
Example 18
Project: MVPAndroidBootstrap-master  File: BaseRetrofitClient.java View source code
public <T> T initRestAdapter(String ENDPOINT, Class<T> restInterface, BaseRetryHandler baseRetryHandler) {
    okHttpClient = new OkHttpClient();
    okHttpClient.setCookieHandler(CookieHandler.getDefault());
    okHttpClient.setConnectTimeout(10, TimeUnit.MINUTES);
    connectivityAwareUrlClient.setWrappedClient(new OkClient(okHttpClient));
    connectivityAwareUrlClient.setRetryHandler(baseRetryHandler);
    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(ENDPOINT).setClient(connectivityAwareUrlClient).build();
    return restAdapter.create(restInterface);
}
Example 19
Project: OkLog-master  File: ApiServiceProvider.java View source code
/**
     * Creates an ApiService.
     * You should use Dagger DI to provide your ApiService, this pattern is used just to simplify the example app.
     *
     * @return ApiService
     */
@NonNull
public static ApiService createApiService() {
    OkLogInterceptor okLogInterceptor = OkLogInterceptor.builder().build();
    OkHttpClient okHttpClient = createOkHttpClient(okLogInterceptor);
    return new RestAdapter.Builder().setClient(new OkClient(okHttpClient)).setEndpoint(Endpoints.newFixedEndpoint(Constants.ENDPOINT)).setLogLevel(LogLevel.FULL).build().create(ApiService.class);
}
Example 20
Project: ParseSendClient-master  File: ApiCreater.java View source code
public static synchronized Api getInstance() {
    if (sharedInstance != null) {
        return sharedInstance;
    }
    RequestInterceptor requestInterceptor = new RequestInterceptor() {

        @Override
        public void intercept(RequestFacade request) {
            request.addHeader(PARSE_APPLICATION_ID, EnvConst.PARSE_APPLICATION_ID);
            request.addHeader(PARSE_REST_API_KEY, EnvConst.PARSE_REST_API_KEY);
        }
    };
    RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint(serverUrl).setRequestInterceptor(requestInterceptor).setClient(new OkClient(new OkHttpClient()));
    if (BuildConfig.DEBUG) {
        builder.setLogLevel(RestAdapter.LogLevel.FULL).setLog(new BetterLog("RETROFIT"));
    }
    return sharedInstance = builder.build().create(Api.class);
}
Example 21
Project: React-Native-Remote-Update-master  File: FrescoModule.java View source code
@Override
public void initialize() {
    super.initialize();
    // Make sure the SoLoaderShim is configured to use our loader for native libraries.
    // This code can be removed if using Fresco from Maven rather than from source
    SoLoaderShim.setHandler(new SoLoaderShim.Handler() {

        @Override
        public void loadLibrary(String libraryName) {
            SoLoader.loadLibrary(libraryName);
        }
    });
    HashSet<RequestListener> requestListeners = new HashSet<>();
    requestListeners.add(new SystraceRequestListener());
    Context context = this.getReactApplicationContext().getApplicationContext();
    OkHttpClient okHttpClient = OkHttpClientProvider.getOkHttpClient();
    ImagePipelineConfig config = OkHttpImagePipelineConfigFactory.newBuilder(context, okHttpClient).setDownsampleEnabled(false).setRequestListeners(requestListeners).build();
    Fresco.initialize(context, config);
}
Example 22
Project: Rutgers-Course-Tracker-master  File: RetroRutgersModule.java View source code
@Provides
@Singleton
public RetroRutgersService providesRutgersRestAdapter(OkHttpClient client, Gson gson) {
    OkHttpClient okClient = client.clone();
    okClient.networkInterceptors().add(getCacheControlInterceptor(TimeUnit.SECONDS.toMillis(5)));
    return new RestAdapter.Builder().setEndpoint("http://sis.rutgers.edu/soc/").setLogLevel(RestAdapter.LogLevel.HEADERS_AND_ARGS).setErrorHandler(new MyErrorHandler()).setClient(new OkClient(okClient)).setConverter(new GsonConverter(gson)).build().create(RetroRutgersService.class);
}
Example 23
Project: The-missing-Android-Guideline-master  File: CheckTaskTest.java View source code
public void test() throws Exception {
    // Create a MockWebServer. These are lean enough that you can create a new
    // instance for every unit test.
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setBody("hello, world!"));
    server.start();
    Bus bus = Mockito.mock(Bus.class);
    new CheckTask(bus, "michaelgruczel", "The-missing-android-guideline", new OkHttpClient()).execute();
    wait(2000);
    Mockito.verify(bus, Mockito.times(1)).post(Matchers.eq(CheckEvent.class));
    server.shutdown();
}
Example 24
Project: uberpay-wallet-master  File: NetworkUtils.java View source code
public static OkHttpClient getHttpClient(Context context) {
    if (httpClient == null) {
        httpClient = new OkHttpClient();
        httpClient.setConnectionSpecs(Collections.singletonList(ConnectionSpec.MODERN_TLS));
        // TODO HTC 300 Crashed due to Network fail - possibly increase timeout rate to 7000 ms
        httpClient.setConnectTimeout(Constants.HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        // Setup cache
        File cacheDir = new File(context.getCacheDir(), Constants.HTTP_CACHE_DIR);
        Cache cache = new Cache(cacheDir, Constants.HTTP_CACHE_SIZE);
        httpClient.setCache(cache);
    }
    return httpClient;
}
Example 25
Project: volleyhelper-master  File: MainActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    VolleyConfiguration configuration = //
    new VolleyConfiguration.Builder(this).builderIsDebug(//
    true).builderHasNoHttpConnectCache(//
    true).builderHttpStack(//
    new OkHttpStack(new OkHttpClient())).builderJsonConvertFactory(new GsonFactory()).builderSetCertificatesFromAssets(//默认�书放在assets目录下,�项�书
    "srca.cer").builderClientKeyManagerFromAssets("srca.cer", "123456").build();
    VolleyHelper.getInstance().init(configuration);
    VolleyHelper.getInstance().loadData(Request.Method.GET, this, "", HelperParams.NET_WORK_ONE);
}
Example 26
Project: AisenWeiBo-master  File: HttpsUtility.java View source code
public OkHttpClient getOkHttpClient() {
    if (mOKHttpClient == null) {
        try {
            mOKHttpClient = new OkHttpClient();
            mOKHttpClient.setConnectTimeout(GlobalContext.CONN_TIMEOUT, TimeUnit.MILLISECONDS);
            mOKHttpClient.setReadTimeout(GlobalContext.READ_TIMEOUT, TimeUnit.MILLISECONDS);
            TrustManager tm = new X509TrustManager() {

                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { tm }, null);
            mOKHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
    return mOKHttpClient;
}
Example 27
Project: android-tutorials-glide-master  File: UnsafeOkHttpClient.java View source code
public static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 28
Project: AndroidProjectTemplate-master  File: AppApplication.java View source code
@AfterInject
public void init() {
    ACRA.init(this);
    ACRA.getErrorReporter().setReportSender(acraSender);
    if (BuildConfig.IS_DEBUGGING) {
        LeakCanary.install(this);
        Stetho.initialize(Stetho.newInitializerBuilder(this).enableDumpapp(Stetho.defaultDumperPluginsProvider(this)).enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this)).build());
    }
    //FOR SAMPLE PURPOSE
    OkHttpClient okHttpClient = new OkHttpClient().setCache(new Cache(getCacheDir(), 1024 * 1024 * 10));
    okHttpClient.setReadTimeout(5, TimeUnit.SECONDS);
    okHttpClient.setRetryOnConnectionFailure(true);
    okHttpClient.setWriteTimeout(1, TimeUnit.MINUTES);
    okHttpClient.setReadTimeout(5, TimeUnit.MINUTES);
    twitterService = new RestAdapter.Builder().setEndpoint("https://api.twitter.com").setConverter(new GsonConverter(new Gson(), "UTF-8")).setClient(new OkClient(okHttpClient)).build().create(TwitterService.class);
}
Example 29
Project: AppCodeArchitecture-master  File: AppApplication.java View source code
private void setUpApiService() {
    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateTypeAdapter()).create();
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(15, TimeUnit.SECONDS);
    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(BuildConfig.API_HOST).setConverter(new GsonConverter(gson)).setClient(new OkClient(okHttpClient)).build();
    sAppApiService = restAdapter.create(AppApiService.class);
}
Example 30
Project: BetaSeries-master  File: BetaSeriesModule.java View source code
@Singleton
@Provides
public BetaSeriesAPI provideBetaSeriesApi(OkHttpClient okHttpClient, AuthenticationManager authenticationManager) {
    return new RestAdapter.Builder().setEndpoint(BuildConfig.URL_BETASERIES).setLogLevel(RestAdapter.LogLevel.FULL).setClient(new OkClient(okHttpClient)).setLog(new AndroidLog("Retrofit")).setRequestInterceptor( request -> {
        request.addHeader("X-BetaSeries-Key", BuildConfig.API_KEY);
        request.addHeader("X-BetaSeries-Version", "2.4");
        request.addHeader("Accept", "application/json");
        String userToken = authenticationManager.getToken();
        if (userToken != null)
            request.addHeader("X-BetaSeries-Token", userToken);
    }).build().create(BetaSeriesAPI.class);
}
Example 31
Project: BiliNyan-Android-master  File: UserInfoApi.java View source code
public static BasicMessage<List> getUserVideoList(int uid, int page) {
    String url = ApiHelper.getUserVideoListUrl(uid, page);
    Request request = new Request.Builder().url(url).header("User-Agent", ApiHelper.COMMON_UA_STR).build();
    Log.i(TAG, "Set up the request" + request.toString());
    BasicMessage<List> msg = new BasicMessage<>();
    try {
        Response response = new OkHttpClient().newCall(request).execute();
        Log.i(TAG, "Get response:" + response.code());
        String result = response.body().string();
        Log.i(TAG, result);
        msg.setObject(List.createFromJson(result));
        msg.setCode(BasicMessage.CODE_SUCCEED);
    } catch (IOException e) {
        e.printStackTrace();
        msg.setCode(BasicMessage.CODE_ERROR);
    }
    return msg;
}
Example 32
Project: CeaselessAndroid-master  File: DownloadFileAsyncTask.java View source code
@Override
protected Void doInBackground(Void... params) {
    Request request = new Request.Builder().url(url).build();
    Response response;
    try {
        OkHttpClient okHttpClient = new OkHttpClient();
        response = okHttpClient.newCall(request).execute();
        BufferedSink sink = Okio.buffer(Okio.sink(this.output));
        sink.writeAll(response.body().source());
        sink.close();
        Log.d(TAG, "downloaded file " + url + " to " + this.output);
    } catch (IOException e) {
        e.printStackTrace();
        Log.e(TAG, "failed to download file " + url);
    }
    return null;
}
Example 33
Project: criticalmaps-android-master  File: TwitterGetHandler.java View source code
@Override
protected ResultType doInBackground(Void... params) {
    final Request request = new Request.Builder().url(Endpoints.GET_TWITTER).get().build();
    final OkHttpClient httpClient = App.components().okHttpClient();
    try {
        final Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            responseString = response.body().string();
            response.body().close();
            return ResultType.SUCCEEDED;
        }
    } catch (Exception ignored) {
    }
    return ResultType.FAILED;
}
Example 34
Project: cw-omnibus-master  File: LoadThread.java View source code
@Override
public void run() {
    try {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(SO_URL).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            Reader in = response.body().charStream();
            BufferedReader reader = new BufferedReader(in);
            SOQuestions questions = new Gson().fromJson(reader, SOQuestions.class);
            reader.close();
            EventBus.getDefault().post(new QuestionsLoadedEvent(questions));
        } else {
            Log.e(getClass().getSimpleName(), response.toString());
        }
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
    }
}
Example 35
Project: DCMonitor-master  File: HttpRequest.java View source code
public static <T> T create(String url, Class<T> clazz) {
    try {
        String hostPart = new URI(url).getHost();
        // Check whether it is a valide url.
        InetAddress.getByName(hostPart);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("The given URI is not valid " + e.getMessage());
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException("The given URI is not valid " + e.getMessage());
    }
    OkHttpClient okHttpClient = new OkHttpClient();
    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(url).setErrorHandler(new HttpErrorHandler()).setClient(new OkClient(okHttpClient)).build();
    return restAdapter.create(clazz);
}
Example 36
Project: GeekBand-Android-1501-Homework-master  File: OkHttpImagePipelineConfigFactory.java View source code
public static ImagePipelineConfig.Builder newBuilder(Context context, OkHttpClient okHttpClient) {
    // Before creating OkHttpNetworkFetchProducer we need to configure and get pool factory -
    // OkHttpNetworkFetchProducer requires pooled byte buffer factory and common byte array pool.
    PoolConfig poolConfig = PoolConfig.newBuilder().build();
    PoolFactory poolFactory = new PoolFactory(poolConfig);
    // Create OkHttpNetworkFetchProducer
    OkHttpNetworkFetchProducer producer = new OkHttpNetworkFetchProducer(okHttpClient, true, poolFactory.getPooledByteBufferFactory(), poolFactory.getCommonByteArrayPool());
    // Pass OkHttpNetworkFetchProducer and PoolFactory we created above the pipeline configuration
    return ImagePipelineConfig.newBuilder(context).setNetworkFetchProducer(producer).setPoolFactory(poolFactory);
}
Example 37
Project: IndiaSatelliteWeather-master  File: HttpClient.java View source code
public static synchronized OkHttpClient getInstance() {
    if (okHttpClient == null) {
        okHttpClient = new OkHttpClient();
        configureDefaultTimeouts();
        initializeHttpCache();
    //TODO: Stetho  library should be included.
    //            okHttpClient.networkInterceptors().add(new StethoInterceptor());
    }
    return okHttpClient;
}
Example 38
Project: kodex-master  File: SecurityConfigurationTestUtils.java View source code
protected Client createHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(0, TimeUnit.MILLISECONDS);
    client.setConnectTimeout(0, TimeUnit.MILLISECONDS);
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(Keystores.loadKeystoreFromResource("security/rhizome.jks", "rhizome".toCharArray()));
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        client.setSslSocketFactory(sslContext.getSocketFactory());
    } catch (NoSuchAlgorithmExceptionKeyManagementException | KeyStoreException | CertificateException | IOException |  e) {
        e.printStackTrace();
    }
    return new OkClient(client);
}
Example 39
Project: mobilecloud-15-master  File: UnsafeHttpsClient.java View source code
public static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 40
Project: open-android-v3-master  File: RetroFitClient.java View source code
private static void setupCitrusRetroFitClient() {
    citrusEndPoint = new CitrusEndPoint(CITRUS_ROOT);
    okHttpClient = new OkHttpClient();
    okHttpClient.setFollowRedirects(false);
    RestAdapter builder = new RestAdapter.Builder().setEndpoint(citrusEndPoint).setClient(new OkClient(okHttpClient)).setLogLevel(CitrusLogger.isEnableLogs() ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE).build();
    RETROFIT_CLIENT = builder.create(API.class);
}
Example 41
Project: OpenMapKit-master  File: NetworkUtils.java View source code
public static HttpURLConnection getHttpURLConnection(final URL url, final Cache cache, final SSLSocketFactory sslSocketFactory) {
    OkHttpClient client = new OkHttpClient();
    if (cache != null) {
        client.setCache(cache);
    }
    if (sslSocketFactory != null) {
        client.setSslSocketFactory(sslSocketFactory);
    }
    HttpURLConnection connection = new OkUrlFactory(client).open(url);
    connection.setRequestProperty("User-Agent", MapboxUtils.getUserAgent());
    return connection;
}
Example 42
Project: osm-contributor-master  File: PresetsModule.java View source code
@Provides
H2GeoPresetsRestClient getH2GeoPresetsRestClient(OkHttpClient okHttpClient) {
    Gson gson = new GsonBuilder().registerTypeAdapter(DateTime.class, new JodaTimeDateTimeDeserializer()).create();
    return new RestAdapter.Builder().setConverter(new GsonConverter(gson)).setEndpoint("https://jawg.github.io/h2geo-presets/").setClient(new OkClient(okHttpClient)).setLogLevel(RestAdapter.LogLevel.FULL).setLog(new AndroidLog("-------------------->")).build().create(H2GeoPresetsRestClient.class);
}
Example 43
Project: paradise-master  File: DataModule.java View source code
@Provides
@Singleton
Picasso providesPicasso(Application app, OkHttpClient client) {
    return new Picasso.Builder(app).downloader(new OkHttpDownloader(client)).listener(new Picasso.Listener() {

        @Override
        public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
            Timber.e(exception, "Failed to load image: %s", uri);
        }
    }).build();
}
Example 44
Project: picasso-helper-master  File: PicassoHelper.java View source code
private static Downloader createDownloader(Context context) {
    boolean okUrlFactory = false;
    try {
        Class.forName("com.squareup.okhttp.OkUrlFactory");
        okUrlFactory = true;
    } catch (ClassNotFoundException ignored) {
    }
    boolean okHttpClient = false;
    try {
        Class.forName("com.squareup.okhttp.OkHttpClient");
        okHttpClient = true;
    } catch (ClassNotFoundException ignored) {
    }
    if (okHttpClient != okUrlFactory) {
        throw new RuntimeException("" + "Picasso detected an unsupported OkHttp on the classpath.\n" + "To use OkHttp with this version of Picasso, you'll need:\n" + "1. com.squareup.okhttp:okhttp:1.6.0 (or newer)\n" + "2. com.squareup.okhttp:okhttp-urlconnection:1.6.0 (or newer)\n" + "Note that OkHttp 2.0.0+ is supported!");
    }
    return okHttpClient ? createOkHttpDownloader(context) : createUrlConnectionDownloader(context);
}
Example 45
Project: PkRSS-master  File: Utils.java View source code
/**
	 * Creates a Downloader object depending on the dependencies present.
	 *
	 * @param context Application context.
	 * @return {@link OkHttp3Downloader} or {@link OkHttpDownloader} if the OkHttp library
	 *          is present, {@link DefaultDownloader} if not.
	 */
public static Downloader createDefaultDownloader(Context context) {
    Downloader downloaderInstance = null;
    try {
        Class.forName("com.squareup.okhttp.OkHttpClient");
        downloaderInstance = new OkHttpDownloader(context);
    } catch (ClassNotFoundException ignored) {
    }
    try {
        Class.forName("okhttp3.OkHttpClient");
        downloaderInstance = new OkHttp3Downloader(context);
    } catch (ClassNotFoundException ignored) {
    }
    if (downloaderInstance == null) {
        downloaderInstance = new DefaultDownloader(context);
    }
    Log.d(TAG, "Downloader is " + downloaderInstance);
    return downloaderInstance;
}
Example 46
Project: poc-android-master  File: RestClient.java View source code
private static void createOKClient() {
    //Set globant Proxy for make API calls inside Globant Company
    //TODO: Change the location of this code
    //System.setProperty("http.proxyHost", "proxy.corp.globant.com");
    //System.setProperty("http.proxyPort", "3128");
    okClient = new OkHttpClient();
    okClient.interceptors().add(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            return response;
        }
    });
}
Example 47
Project: PocketHub-master  File: ImageBinPoster.java View source code
/**
     * Post the image to ImageBin
     *
     * @param bytes Bytes of the image to post
     * @param callback Request callback
     */
public static void post(byte[] bytes, Callback callback) {
    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("file", "test", RequestBody.create(MediaType.parse("image/*"), bytes)).build();
    Request request = new Request.Builder().url("https://imagebin.ca/upload.php").post(requestBody).build();
    OkHttpClient client = new OkHttpClient();
    Call call = client.newCall(request);
    call.enqueue(callback);
}
Example 48
Project: pola-android-master  File: PolaApplication.java View source code
@Override
public void onCreate() {
    super.onCreate();
    component = PolaComponent.Initializer.init(this);
    if (BuildConfig.USE_CRASHLYTICS) {
        Fabric.with(this, new Crashlytics());
    }
    ButterKnife.setDebug(BuildConfig.DEBUG);
    if (BuildConfig.DEBUG) {
        Timber.plant(new Timber.DebugTree());
    } else {
        Timber.plant(new CrashReportingTree());
    }
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(Utils.TIMEOUT_SECONDS, TimeUnit.SECONDS);
    client.setReadTimeout(Utils.TIMEOUT_SECONDS, TimeUnit.SECONDS);
    retrofit = new Retrofit.Builder().baseUrl(this.getResources().getString(R.string.pola_api_url)).addConverterFactory(GsonConverterFactory.create()).client(client).build();
}
Example 49
Project: ProconAppAndroid-master  File: BaseApi.java View source code
/** 実際�通信処�を行� */
protected void execute(Request req) {
    mResponseObj = null;
    mResponseBodyText = null;
    mResponseStatusCode = -1;
    OkHttpClient client = new OkHttpClient();
    ResponseBody body = null;
    try {
        Response res = client.newCall(req).execute();
        mResponseStatusCode = res.code();
        body = res.body();
        if (isResponseOk(res)) {
            mResponseBodyText = body.string();
        } else {
            Timber.e("execute: failed request code=" + res.code());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (body != null) {
            try {
                body.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 50
Project: programming-cloud-services-for-android-master  File: UnsafeHttpsClient.java View source code
public static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 51
Project: progscrape-android-master  File: FooTest.java View source code
@Test
public void testHi() throws InterruptedException {
    final OkHttpClient client = new OkHttpClient();
    RequestExecutor executor = new RequestExecutor() {

        @Override
        public <T> void execute(OkHttpSpiceRequest<T> req, RequestListener<T> listener, boolean force) {
            req.setOkHttpClient(client);
            try {
                listener.onRequestSuccess(req.loadDataFromNetwork());
            } catch (Exception e) {
                listener.onRequestFailure(new SpiceException(e));
            }
        }
    };
    Data data = new Data(executor, new FeedParser());
    final CountDownLatch latch = new CountDownLatch(1);
    data.getStoryData(null, new RequestListener<List<Story>>() {

        @Override
        public void onRequestFailure(SpiceException spiceException) {
            System.out.println(spiceException);
            latch.countDown();
        }

        @Override
        public void onRequestSuccess(List<Story> stories) {
            System.out.println(stories);
            latch.countDown();
        }
    }, false);
    if (!latch.await(10, TimeUnit.SECONDS))
        fail("Timeout");
}
Example 52
Project: RedisBungee-master  File: UUIDNameTest.java View source code
@Test
public void testUuidToName() throws IOException {
    OkHttpClient httpClient = new OkHttpClient();
    NameFetcher.setHttpClient(httpClient);
    for (String uuid : uuidsToTest) {
        List<String> names = NameFetcher.nameHistoryFromUuid(UUIDFetcher.getUUID(uuid));
        String currentName = names.get(names.size() - 1);
        System.out.println("Current name for UUID " + uuid + " is " + currentName);
    }
}
Example 53
Project: remusic-master  File: RestServiceFactory.java View source code
public static <T> T create(final Context context, String baseUrl, Class<T> clazz) {
    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setCache(new Cache(context.getApplicationContext().getCacheDir(), CACHE_SIZE));
    okHttpClient.setConnectTimeout(40, TimeUnit.SECONDS);
    RequestInterceptor interceptor = new RequestInterceptor() {

        @Override
        public void intercept(RequestFacade request) {
            //7-days cache
            request.addHeader("Cache-Control", String.format("max-age=%d,max-stale=%d", Integer.valueOf(60 * 60 * 24 * 7), Integer.valueOf(31536000)));
            request.addHeader("Connection", "keep-alive");
        }
    };
    RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint(baseUrl).setRequestInterceptor(interceptor).setClient(new OkClient(okHttpClient));
    return builder.build().create(clazz);
}
Example 54
Project: RSSTS-master  File: SlackClient.java View source code
public static void initialize() {
    RestAdapter.Log restLogs = new RestAdapter.Log() {

        @Override
        public void log(String s) {
            LogUtils.D("CLIENT", s);
        }
    };
    // create client
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
    okHttpClient.setWriteTimeout(1, TimeUnit.MINUTES);
    okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);
    //slack
    RestAdapter slackRestAdapter = new RestAdapter.Builder().setEndpoint(BASE_API).setLog(restLogs).setClient(new OkClient(okHttpClient)).setLogLevel(RestAdapter.LogLevel.FULL).build();
    sSlack = slackRestAdapter.create(Slack.class);
}
Example 55
Project: sendtopulsar-master  File: DataModule.java View source code
static OkHttpClient createOkHttpClient(SendToPulsarApp app) {
    OkHttpClient client = new OkHttpClient();
    // Install an HTTP cache in the application cache directory.
    try {
        File cacheDir = new File(app.getCacheDir(), "http");
        Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
        client.setCache(cache);
    } catch (IOException e) {
        Log.e(TAG, "Unable to install disk cache.", e);
    }
    return client;
}
Example 56
Project: shopnc-app-master  File: ServiceGenerator.java View source code
public static <S> S createService(Class<S> serviceClass, String baseUrl, final String apiToken) {
    RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint(baseUrl).setClient(new OkClient(new OkHttpClient()));
    if (apiToken != null) {
        builder.setRequestInterceptor(new RequestInterceptor() {

            @Override
            public void intercept(RequestInterceptor.RequestFacade request) {
                request.addHeader("Authorization", "Token");
                request.addHeader("Accept", "application/json");
            }
        });
    }
    RestAdapter adapter = builder.build();
    return adapter.create(serviceClass);
}
Example 57
Project: slack-capybara-master  File: MisawaHandlers.java View source code
@Override
public void register(final Robot robot) {
    robot.respond("(?i)misawa\\z", "returns JIGOKU-NO-MISAWA image",  message -> {
        final OkHttpClient client = new OkHttpClient();
        final String url = "http://horesase.github.io/horesase-boys/meigens.json";
        final Request request = new Request.Builder().url(url).build();
        try {
            final Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                final String src = response.body().string();
                final Type collectionType = new TypeToken<Collection<Meigen>>() {
                }.getType();
                final List<Meigen> rootAsMap = new Gson().fromJson(src, collectionType);
                message.reply(BotanUtils.getRandomValue(rootAsMap).image);
            } else {
                message.reply(ERROR_PREFIX + String.format("http request failed (%d)", response.code()));
            }
        } catch (IOException e) {
            log.warn(e.getMessage());
            message.reply(ERROR_PREFIX + e.getMessage());
        }
    });
}
Example 58
Project: Spark_Pixels-master  File: WebHelpers.java View source code
// should be called during Application.onCreate() to ensure availability
public static void initialize(Context ctx) {
    if (!initialized) {
        if (AppConfig.useStaging()) {
            okHttpClient = disableTLSforStaging();
        } else {
            okHttpClient = new OkHttpClient();
        }
        gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
        initialized = true;
    }
}
Example 59
Project: sthlmtraveling-master  File: ApiServiceProvider.java View source code
public static RestAdapter getRestAdapter(OkHttpClient client) {
    RequestInterceptor requestInterceptor = new RequestInterceptor() {

        @Override
        public void intercept(RequestFacade request) {
            request.addHeader("User-Agent", AppConfig.USER_AGENT);
            request.addHeader("X-STHLMTraveling-API-Key", AppConfig.STHLM_TRAVELING_API_KEY);
        }
    };
    return new RestAdapter.Builder().setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE).setEndpoint(AppConfig.STHLM_TRAVELING_API_ENDPOINT).setConverter(new GsonConverter(GsonProvider.provideGson())).setRequestInterceptor(requestInterceptor).setClient(new OkClient(client)).build();
}
Example 60
Project: strapkit_wear-master  File: HttpClient.java View source code
public void processHTTPCall(final HttpClientCallback callback) {
    OkHttpClient httpClient = new OkHttpClient();
    Request.Builder requestBuilder = new Request.Builder().url(url);
    Request request = null;
    if (TextUtils.isEmpty(this.method)) {
        this.method = GET;
    }
    switch(this.method) {
        case POST:
            break;
        case PUT:
            break;
        case DELETE:
            break;
        default:
            request = requestBuilder.get().build();
            break;
    }
    try {
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            if (callback != null) {
                callback.OnHttpComplete(success, response.body().string());
            }
        } else {
            if (callback != null) {
                callback.OnHttpComplete(failure, "'" + response.message() + "'");
            }
        }
    } catch (Exception e) {
        if (callback != null) {
            callback.OnHttpComplete(failure, "'" + e.getMessage() + "'");
        }
    }
}
Example 61
Project: SyncthingAndroid-master  File: SyncthingApiModule.java View source code
@Provides
@SessionScope
public SyncthingApi provideSyncthingApi(Gson gson, OkHttpClient okClient, SyncthingApiConfig config) {
    OkHttpClient client = okClient.clone();
    client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setSslSocketFactory(SyncthingSSLSocketFactory.create(config.getCACert()));
    client.setHostnameVerifier(new NullHostNameVerifier());
    client.interceptors().add(new SyncthingApiInterceptor(config));
    Retrofit.Builder b = new Retrofit.Builder().addCallAdapterFactory(RxJavaCallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create(gson)).client(client).baseUrl(config.getBaseUrl());
    if (BuildConfig.DEBUG) {
        b.validateEagerly();
    }
    return b.build().create(SyncthingApi.class);
}
Example 62
Project: Tower-master  File: NetworkUtils.java View source code
public static HttpURLConnection getHttpURLConnection(final URL url, final Cache cache, final SSLSocketFactory sslSocketFactory) {
    OkHttpClient client = new OkHttpClient();
    if (cache != null) {
        client.setCache(cache);
    }
    if (sslSocketFactory != null) {
        client.setSslSocketFactory(sslSocketFactory);
    }
    HttpURLConnection connection = new OkUrlFactory(client).open(url);
    connection.setRequestProperty("User-Agent", MapboxUtils.getUserAgent());
    return connection;
}
Example 63
Project: triaina-master  File: FixedHttpClient.java View source code
public static synchronized OkHttpClient getInstance() {
    if (sOkHttpClient == null) {
        sOkHttpClient = new OkHttpClient();
        sOkHttpClient.setConnectTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
        sOkHttpClient.setReadTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
        sOkHttpClient.setWriteTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
        sOkHttpClient.networkInterceptors().add(new UserAgentInterceptor(getUserAgentString()));
    }
    return sOkHttpClient;
}
Example 64
Project: TruckMuncher-Android-master  File: DebugModule.java View source code
private static void configureSsl(OkHttpClient client) {
    try {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            @Override
            public void checkClientTrusted(@NonNull X509Certificate[] certs, @NonNull String authType) {
            }

            @Override
            public void checkServerTrusted(@NonNull X509Certificate[] certs, @NonNull String authType) {
            }
        } };
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        client.setSslSocketFactory(sc.getSocketFactory());
        client.setHostnameVerifier(new AllowAllHostnameVerifier());
    } catch (Exception e) {
        Timber.e(e, "Couldn't configure SSL");
    }
}
Example 65
Project: U2020-mortar-flow-master  File: DataModule.java View source code
@Provides
@Singleton
Picasso providePicasso(Application app, OkHttpClient client) {
    return new Picasso.Builder(app).downloader(new OkHttpDownloader(client)).listener(new Picasso.Listener() {

        @Override
        public void onImageLoadFailed(Picasso picasso, Uri uri, Exception e) {
            Timber.e(e, "Failed to load image: %s", uri);
        }
    }).build();
}
Example 66
Project: udacity-popular-movies-master  File: DataModule.java View source code
static OkHttpClient createOkHttpClient(Application app) {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, SECONDS);
    client.setReadTimeout(10, SECONDS);
    client.setWriteTimeout(10, SECONDS);
    // Install an HTTP cache in the application cache directory.
    File cacheDir = new File(app.getCacheDir(), "http");
    Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
    client.setCache(cache);
    return client;
}
Example 67
Project: WearSquare-master  File: Api.java View source code
public static Retrofit get() {
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            HttpUrl newUrl = originalRequest.httpUrl().newBuilder().addQueryParameter("v", BUILD_DATE).addQueryParameter("oauth_token", Preferences.getFoursquareToken()).build();
            Request newRequest = originalRequest.newBuilder().url(newUrl).build();
            L.i("Calling " + newUrl);
            Response response = chain.proceed(newRequest);
            L.i("Response code: " + response.code());
            return response;
        }
    });
    return new Retrofit.Builder().baseUrl(URL).client(client).addConverterFactory(GsonConverterFactory.create()).build();
}
Example 68
Project: WeiBo_LH-master  File: App.java View source code
private void init() {
    DisplayMetrics dm = getResources().getDisplayMetrics();
    SCREEN_WIDTH = Math.min(dm.widthPixels, dm.heightPixels);
    SCREEN_HEIGHT = Math.max(dm.widthPixels, dm.heightPixels);
    OkHttpClient client = new OkHttpClient();
    File cacheDirectory = new File(Config.CACHE_DIR);
    if (!cacheDirectory.exists()) {
        cacheDirectory.mkdirs();
    }
    final Cache cache = new Cache(cacheDirectory, Config.CACHE_SIZE);
    client.setCache(cache);
    mRestAdapter = new RestAdapter.Builder().setEndpoint(Constants.BASE_URL).setClient(new OkClient(client)).setRequestInterceptor(new RequestInterceptor() {

        @Override
        public void intercept(RequestFacade request) {
            if (Network.isConnected(getApplicationContext())) {
                // read from cache for 1 minute
                int maxAge = 2;
                request.addHeader("Cache-Control", "public, max-age=" + maxAge);
            } else {
                // tolerate 4-weeks stale
                int maxStale = 60 * 60 * 24 * 28;
                request.addHeader("Cache-Control", "public, only-if-cached, max-stale=" + maxStale);
            }
        }
    }).build();
}
Example 69
Project: WhereIsMyCurrency-master  File: ApiModule.java View source code
private static OkHttpClient createOkHttpClient(Application application) {
    final OkHttpClient temporaryClient = new OkHttpClient();
    temporaryClient.networkInterceptors().add(new StethoInterceptor());
    try {
        File cacheDirectory = application.getCacheDir();
        Cache cache = new Cache(cacheDirectory, DISK_CACHE_SIZE);
        temporaryClient.setCache(cache);
    } catch (Exception e) {
        if (BuildConfig.DEBUG) {
            Log.e(TAG, "Unable to initialize OkHttpClient with disk cache.");
        }
    }
    return temporaryClient;
}
Example 70
Project: yyl-master  File: MySSLTrust.java View source code
@SuppressWarnings("null")
public static OkHttpClient configureClient(final OkHttpClient client) {
    final TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
        }
    } };
    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (final java.security.GeneralSecurityException ex) {
    }
    try {
        final HostnameVerifier hostnameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(final String hostname, final SSLSession session) {
                return true;
            }
        };
        client.setHostnameVerifier(hostnameVerifier);
        client.setSslSocketFactory(new SSLv3SocketFactory(ctx.getSocketFactory()));
    } catch (final Exception e) {
    }
    return client;
}
Example 71
Project: wasp-master  File: OkHttpStack.java View source code
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
    OkHttpClient okHttpClient = client.clone();
    int timeoutMs = request.getTimeoutMs();
    okHttpClient.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    okHttpClient.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    okHttpClient.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder();
    builder.url(request.getUrl());
    Map<String, String> headers = request.getHeaders();
    for (String name : headers.keySet()) {
        builder.addHeader(name, headers.get(name));
    }
    for (String name : additionalHeaders.keySet()) {
        builder.addHeader(name, additionalHeaders.get(name));
    }
    setConnectionParametersForRequest(builder, request);
    Call okHttpCall = okHttpClient.newCall(builder.build());
    Response okHttpResponse = okHttpCall.execute();
    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));
    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }
    return response;
}
Example 72
Project: actor-platform-master  File: ActorPushRegister.java View source code
public static void registerForPush(final Context context, String endpoint, final Callback callback) {
    Runtime.dispatch(() -> {
        final SharedPreferences sharedPreferences = context.getSharedPreferences("actor_push_register", Context.MODE_PRIVATE);
        String registrationEndpoint = sharedPreferences.getString("registration_endpoint", null);
        String registrationData = sharedPreferences.getString("registration_data", null);
        OkHttpClient client = new OkHttpClient();
        if (registrationEndpoint != null && registrationData != null) {
            try {
                JSONObject data = new JSONObject(registrationData);
                startService(data, context);
                callback.onRegistered(registrationEndpoint);
                return;
            } catch (JSONException e) {
                e.printStackTrace();
                sharedPreferences.edit().clear().commit();
            }
        }
        final Request request = new Request.Builder().url(endpoint).method("POST", RequestBody.create(MediaType.parse("application/json"), "{}")).build();
        client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {

            @Override
            public void onFailure(Request request, IOException e) {
                Log.d("ACTOR_PUSH", "ACTOR_PUSH not registered: " + e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String res = response.body().string();
                    JSONObject js = new JSONObject(res).getJSONObject("data");
                    String endpoint1 = js.getString("endpoint");
                    sharedPreferences.edit().putString("registration_endpoint", endpoint1).putString("registration_data", js.toString()).commit();
                    startService(js, context);
                    Log.d("ActorPushRegister", "Endpoint: " + endpoint1);
                    callback.onRegistered(endpoint1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    });
}
Example 73
Project: Android-CleanArchitecture-master  File: ApiConnection.java View source code
private void connectToApi() {
    OkHttpClient okHttpClient = this.createClient();
    final Request request = new Request.Builder().url(this.url).addHeader(CONTENT_TYPE_LABEL, CONTENT_TYPE_VALUE_JSON).get().build();
    try {
        this.response = okHttpClient.newCall(request).execute().body().string();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 74
Project: apiman-master  File: OkUrlFactory.java View source code
HttpURLConnection open(URL url, Proxy proxy) {
    String protocol = url.getProtocol();
    OkHttpClient copy = client.clone();
    if (protocol.equals("http"))
        return new HttpURLConnectionImpl(url, copy);
    if (protocol.equals("https"))
        return new HttpsURLConnectionImpl(url, copy);
    throw new IllegalArgumentException("Unexpected protocol: " + protocol);
}
Example 75
Project: Artbook-master  File: DribbbleFetch.java View source code
public void load(final ArtbookActivity caller, String url) {
    mIsLoading = true;
    new AsyncTask<String, Void, String>() {

        OkHttpClient client = new OkHttpClient();

        private Exception exception;

        protected String doInBackground(String... urls) {
            try {
                return get(new URL(urls[0]));
            } catch (Exception e) {
                this.exception = e;
                Log.e(TAG, "Exception: " + e);
                return null;
            }
        }

        protected void onPostExecute(String data) {
            DribbbleFeed feed = new Gson().fromJson(data, DribbbleFeed.class);
            if (feed == null) {
                caller.onDataFailed();
            }
            caller.onDataLoaded(feed);
            mIsLoading = false;
        }

        String get(URL url) throws IOException {
            HttpURLConnection connection = client.open(url);
            InputStream in = null;
            try {
                in = connection.getInputStream();
                byte[] response = readFully(in);
                return new String(response, "UTF-8");
            } finally {
                if (in != null)
                    in.close();
            }
        }

        byte[] readFully(InputStream in) throws IOException {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            for (int count; (count = in.read(buffer)) != -1; ) {
                out.write(buffer, 0, count);
            }
            return out.toByteArray();
        }
    }.execute(url);
}
Example 76
Project: BitcoinBlue-master  File: DataModule.java View source code
static OkHttpClient createOkHttpClient(BaseApplication app) {
    OkHttpClient client = new OkHttpClient();
    // Install an HTTP cache in the application cache directory.
    try {
        File cacheDir = new File(app.getCacheDir(), "http");
        Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
        client.setCache(cache);
    } catch (Exception e) {
        Timber.e(e, "Unable to install disk cache.");
    }
    return client;
}
Example 77
Project: CopyOfNetEase-master  File: RestHttpClient.java View source code
public void doGet(Object tag, String paramsUrl, Header[] headers, BaseApiHandler baseHandler) {
    LayzLog.i("url = %s", paramsUrl);
    if (headers != null) {
        LayzLog.i("headers = %s", headers.toString());
    }
    LayzLog.i("url = %s", paramsUrl);
    OkHttpClient mOkHttpClient = AsynHttpClientUtil.INSTANCE.getInstance();
    request(RequestType.GET, mOkHttpClient, paramsUrl, headers, tag, baseHandler);
}
Example 78
Project: DoubanTop-master  File: DoubanApiUtils.java View source code
// sigleton
public static DoubanMovieApiService getMovieApiService() {
    if (mApiService == null) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        mOkHttpClient.setConnectTimeout(15, TimeUnit.SECONDS);
        RestAdapter restAdapter = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.FULL).setEndpoint(DOUBAN_API_V2_BASE_URI).setClient(new OkClient(mOkHttpClient)).build();
        mApiService = restAdapter.create(DoubanMovieApiService.class);
    }
    return mApiService;
}
Example 79
Project: episodes-master  File: EpisodesApplication.java View source code
@Override
public void onCreate() {
    super.onCreate();
    instance = this;
    // ensure the default settings are initialised at first launch,
    // rather than waiting for the settings screen to be opened.
    // do this before anything that needs these settings is instantiated.
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    autoRefreshHelper = AutoRefreshHelper.getInstance(this);
    httpClient = new OkHttpClient();
    try {
        Cache httpCache = new Cache(getCacheDir(), 1024 * 1024);
        httpClient.setCache(httpCache);
    } catch (IOException e) {
        Log.w(TAG, "Error initialising okhttp cache", e);
    }
    final ImageLoaderConfiguration imageLoaderConfig = new ImageLoaderConfiguration.Builder(this).build();
    ImageLoader.getInstance().init(imageLoaderConfig);
}
Example 80
Project: evercam-play-android-master  File: SaveImageRunnable.java View source code
private Bitmap requestForBitmapByUrl() {
    try {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(thumbnailUrl).build();
        Response response = client.newCall(request).execute();
        return BitmapFactory.decodeStream(response.body().byteStream());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
        return null;
    }
}
Example 81
Project: fluent-rest-test-master  File: RestResponse.java View source code
static RestResponse call(String url, Function<OkHttpClient, OkHttpClient> configureClient, Function<Request.Builder, Request.Builder> configureRequest) throws IOException {
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(ACCEPT_ALL);
    Request.Builder request = configureRequest.apply(new Request.Builder().url(url));
    OkHttpClient client = configureClient.apply(new OkHttpClient().setCookieHandler(cookieManager));
    Response response = client.newCall(request.build()).execute();
    return new RestResponse(cookieManager, response);
}
Example 82
Project: FreeFlow-master  File: DribbbleFetch.java View source code
public void load(final ArtbookActivity caller, int itemsPerPage, int page) {
    new AsyncTask<String, Void, String>() {

        OkHttpClient client = new OkHttpClient();

        private Exception exception;

        protected String doInBackground(String... urls) {
            try {
                return get(new URL(urls[0]));
            } catch (Exception e) {
                this.exception = e;
                Log.e(TAG, "Exception: " + e);
                return null;
            }
        }

        protected void onPostExecute(String data) {
            DribbbleFeed feed = new Gson().fromJson(data, DribbbleFeed.class);
            caller.onDataLoaded(feed);
        }

        String get(URL url) throws IOException {
            HttpURLConnection connection = client.open(url);
            InputStream in = null;
            try {
                in = connection.getInputStream();
                byte[] response = readFully(in);
                return new String(response, "UTF-8");
            } finally {
                if (in != null)
                    in.close();
            }
        }

        byte[] readFully(InputStream in) throws IOException {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            for (int count; (count = in.read(buffer)) != -1; ) {
                out.write(buffer, 0, count);
            }
            return out.toByteArray();
        }
    }.execute("http://api.dribbble.com/shots/popular?per_page=" + itemsPerPage + "&page=" + page);
}
Example 83
Project: iFixitAndroid-master  File: PicassoUtils.java View source code
public static Picasso with(Context context) {
    // Mimicking Picasso's new OkHttpLoader(context), but with our custom OkHttpClient
    if (singleton == null) {
        OkHttpClient client = Utils.createOkHttpClient();
        try {
            client.setResponseCache(createResponseCache(context));
        } catch (IOException ignored) {
        }
        singleton = new Picasso.Builder(context).downloader(new OkHttpDownloader(client)).build();
    }
    return singleton;
}
Example 84
Project: IU-master  File: RemoteHelper.java View source code
/**
     * Download an object from the network.
     * 
     * @param resourceUrl The URL of then rsource.
     * @throws IOException If the connection cannot be established.
     * @return Byte array of the downloaded object.
     */
public static byte[] download(String resourceUrl) throws IOException {
    OkHttpClient client = new OkHttpClient();
    URL url = new URL(resourceUrl);
    HttpURLConnection connection = client.open(url);
    final int responseCode = connection.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        Logcat.w(LOG_TAG, "Downloading from URL " + resourceUrl + " failed with response code " + responseCode);
        return null;
    }
    // determine the image size and allocate a buffer
    int fileSize = connection.getContentLength();
    Logcat.d(LOG_TAG, "fetching " + resourceUrl + " (" + (fileSize <= 0 ? "size unknown" : Integer.toString(fileSize)) + ")");
    BufferedInputStream istream = new BufferedInputStream(connection.getInputStream());
    try {
        if (fileSize <= 0) {
            Logcat.w(LOG_TAG, "Server did not set a Content-Length header, will default to buffer size of " + defaultBufferSize + " bytes");
            ByteArrayOutputStream buf = new ByteArrayOutputStream(defaultBufferSize);
            byte[] buffer = new byte[defaultBufferSize];
            int bytesRead = 0;
            while (bytesRead != -1) {
                bytesRead = istream.read(buffer, 0, defaultBufferSize);
                if (bytesRead > 0) {
                    buf.write(buffer, 0, bytesRead);
                }
            }
            return buf.toByteArray();
        } else {
            byte[] data = new byte[fileSize];
            int bytesRead = 0;
            int offset = 0;
            while (bytesRead != -1 && offset < fileSize) {
                bytesRead = istream.read(data, offset, fileSize - offset);
                offset += bytesRead;
            }
            return data;
        }
    } finally {
        // clean up
        try {
            istream.close();
            connection.disconnect();
        } catch (Exception ignore) {
        }
    }
}
Example 85
Project: jclouds-master  File: DockerOkHttpClientSupplier.java View source code
@Override
public OkHttpClient get() {
    OkHttpClient client = new OkHttpClient();
    ConnectionSpec tlsSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).tlsVersions(TlsVersion.TLS_1_0, TlsVersion.TLS_1_1, TlsVersion.TLS_1_2).build();
    ConnectionSpec cleartextSpec = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT).build();
    client.setConnectionSpecs(ImmutableList.of(tlsSpec, cleartextSpec));
    // check if identity and credential are files, to set up sslContext
    if (new File(creds.get().identity).isFile() && new File(creds.get().credential).isFile()) {
        client.setSslSocketFactory(dockerSSLContextSupplier.get().getSocketFactory());
    }
    return client;
}
Example 86
Project: js-android-sdk-master  File: TestKitClient.java View source code
public static TestKitClient newClient(String baseUrl, Proxy proxy) {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setCookieHandler(LocalCookieManager.get());
    if (proxy != null) {
        okHttpClient.setProxy(proxy);
    }
    GetResourcesUrisUseCase getResourcesUrisUseCase = new GetResourcesUrisUseCase(okHttpClient, baseUrl);
    GetReportParametersUseCase getReportParametersUseCase = new GetReportParametersUseCase(okHttpClient, baseUrl);
    GetServerInfoUseCase getServerInfoUseCase = new GetServerInfoUseCase(okHttpClient, baseUrl);
    return new TestKitClient(getResourcesUrisUseCase, getReportParametersUseCase, getServerInfoUseCase);
}
Example 87
Project: kc-android-master  File: DataModule.java View source code
static OkHttpClient createOkHttpClient(Application app) {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(SOCKET_TIMEOUT, TimeUnit.SECONDS);
    client.setReadTimeout(SOCKET_TIMEOUT, TimeUnit.SECONDS);
    // Install an HTTP cache in the application cache directory.
    try {
        File cacheDir = new File(app.getCacheDir(), "http");
        Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
        client.setCache(cache);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return client;
}
Example 88
Project: KDIC-Radio-Android-master  File: GetSchedule.java View source code
@Override
protected Boolean doInBackground(Void... params) {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(Constants.SCHEDULE_URL).build();
    try {
        Response response = client.newCall(request).execute();
        Schedule schedule = new Schedule(context);
        // Parse JSON and add it to SQLite DB
        schedule.updateSchedule(response.body().string());
        // successfully updated schedule
        return true;
    } catch (IOExceptionJSONException |  e) {
        e.printStackTrace();
    }
    // failed to update schedule
    return false;
}
Example 89
Project: KingsCrossApp-master  File: DataModule.java View source code
static OkHttpClient createOkHttpClient(Application app) {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(SOCKET_TIMEOUT, TimeUnit.SECONDS);
    client.setReadTimeout(SOCKET_TIMEOUT, TimeUnit.SECONDS);
    // Install an HTTP cache in the application cache directory.
    try {
        File cacheDir = new File(app.getCacheDir(), "http");
        Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
        client.setCache(cache);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return client;
}
Example 90
Project: mifos-twilio-bridge-master  File: RestAdapterProvider.java View source code
@SuppressWarnings("unused")
public OkHttpClient createClient() {
    final OkHttpClient client = new OkHttpClient();
    final TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
        }
    } };
    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (final java.security.GeneralSecurityException ex) {
    }
    try {
        final HostnameVerifier hostnameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(final String hostname, final SSLSession session) {
                return true;
            }
        };
        client.setHostnameVerifier(hostnameVerifier);
        client.setSslSocketFactory(ctx.getSocketFactory());
    } catch (final Exception e) {
    }
    return client;
}
Example 91
Project: MIFOSX-master  File: ProcessorHelper.java View source code
@SuppressWarnings("null")
public static OkHttpClient configureClient(final OkHttpClient client) {
    final TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
        }
    } };
    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (final java.security.GeneralSecurityException ex) {
    }
    try {
        final HostnameVerifier hostnameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(final String hostname, final SSLSession session) {
                return true;
            }
        };
        client.setHostnameVerifier(hostnameVerifier);
        client.setSslSocketFactory(ctx.getSocketFactory());
    } catch (final Exception e) {
    }
    return client;
}
Example 92
Project: MOE-master  File: GithubClient.java View source code
String getResponseJson(PullRequestUrl id) {
    Request request = new Request.Builder().url(id.apiAddress()).addHeader("User-Agent", "OkHttpClient/1.0 (Make Open Easy repository sync software)").build();
    try {
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            switch(response.code()) {
                case 404:
                    throw new InvalidGithubUrl("No such pull request found: %s", id);
                case 403:
                    throw new InvalidGithubUrl("Github rate-limit reached - please wait 60 mins: %s", id);
                default:
                    throw new IOException("Unexpected code " + response);
            }
        }
        return response.body().string();
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
Example 93
Project: mshopping-android-master  File: ApiFacade.java View source code
private RestAdapter getRestAdapter() {
    OkHttpClient okHttpClient = new OkHttpClient();
    RestAdapter builder = new RestAdapter.Builder().setClient(new OkClient(okHttpClient)).setEndpoint("http://10.68.102.241:8080").setRequestInterceptor(alipushInterceptor).setErrorHandler(alipushErrorHandler).setConverter(new JsonConverter()).setLogLevel(RestAdapter.LogLevel.FULL).build();
    return builder;
}
Example 94
Project: OneDriveJavaSDK-master  File: SessionProvider.java View source code
private static OneDriveSession openSession() throws IOException, OneDriveException {
    final OneDriveSession session = OneDriveSession.initializeSession(new OkHttpClient(), clientID, clientSecret, null, new OneDriveScope[] { OneDriveScope.SIGNIN, OneDriveScope.OFFLINE_ACCESS, OneDriveScope.READWRITE });
    openWebpage(new URL(session.getAccessURL()));
    // JUnit Interactivit workaround ... bad but hey...
    final JFrame f = new JFrame("OAuthCode");
    final JTextField codeField = new JTextField();
    codeField.setPreferredSize(new Dimension(100, 21));
    JButton send = new JButton("send");
    f.setLayout(new FlowLayout(FlowLayout.LEFT));
    f.add(codeField);
    f.add(send);
    send.addActionListener(new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                OneDriveSession.authorizeSession(session, codeField.getText());
            } catch (OneDriveException e1) {
                e1.printStackTrace();
            }
            f.dispose();
        }
    });
    f.pack();
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    while (!session.isAuthenticated()) {
        Thread.yield();
    }
    OneDriveSession.write(session, sessionFile);
    return session;
}
Example 95
Project: orc-for-android-master  File: OkHttpNetworkRunnable.java View source code
@Override
public void run() {
    try {
        OkHttpClient client = new OkHttpClient();
        client.networkInterceptors().add(new LoggingInterceptor());
        RequestBody requestBody = null;
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        if (mRequest.getStreamedContent() != null) {
            requestBody = new StreamedRequest(mediaType, mRequest);
        } else if (mRequest.getContent() != null) {
            requestBody = RequestBody.create(mediaType, mRequest.getContent());
        }
        if (requestBody == null && (mRequest.getVerb().toString().equals("POST") || mRequest.getVerb().toString().equals("PUT"))) {
            requestBody = RequestBody.create(null, new byte[0]);
        }
        Request request = new Request.Builder().url(mRequest.getUrl().toString()).method(mRequest.getVerb().toString(), requestBody).headers(Headers.of(mRequest.getHeaders())).build();
        Response okResponse = client.newCall(request).execute();
        int status = okResponse.code();
        final ResponseBody responseBody = okResponse.body();
        InputStream stream = null;
        if (responseBody != null) {
            stream = responseBody.byteStream();
        }
        if (stream != null) {
            Closeable closeable = new Closeable() {

                @Override
                public void close() throws IOException {
                    responseBody.close();
                }
            };
            com.microsoft.services.orc.http.Response response = new ResponseImpl(stream, status, okResponse.headers().toMultimap(), closeable);
            mFuture.set(response);
        } else {
            mFuture.set(new EmptyResponse(status, okResponse.headers().toMultimap()));
        }
    } catch (Throwable t) {
        t.printStackTrace();
        mFuture.setException(t);
    }
}
Example 96
Project: Pioneer-master  File: DataModule.java View source code
@Provides
@Singleton
Picasso providePicasso(Application app, OkHttpClient client) {
    return new Picasso.Builder(app).downloader(new OkHttpDownloader(client)).listener(new Picasso.Listener() {

        @Override
        public void onImageLoadFailed(Picasso picasso, Uri uri, Exception e) {
            Timber.e(e, "Failed to load image: %s", uri);
        }
    }).build();
}
Example 97
Project: ponyville-live-android-master  File: NetModule.java View source code
public static OkHttpClient createOkHttpClient(Application app) {
    OkHttpClient client = new OkHttpClient();
    // Install an HTTP cache in the application cache directory.
    try {
        File cacheDir = new File(app.getCacheDir(), "http");
        Cache cache = new Cache(cacheDir, CACHE_SIZE);
        client.setCache(cache);
    } catch (IOException e) {
        Timber.e(e, "Unable to install disk cache.");
    }
    return client;
}
Example 98
Project: Rocko-Android-Demos-master  File: ApiConnection.java View source code
private void connectToApi() {
    OkHttpClient okHttpClient = this.createClient();
    final Request request = new Request.Builder().url(this.url).addHeader(CONTENT_TYPE_LABEL, CONTENT_TYPE_VALUE_JSON).get().build();
    try {
        this.response = okHttpClient.newCall(request).execute().body().string();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 99
Project: ru-direct-master  File: NextBusAPI.java View source code
// Downloads data from a url and returns it as an input stream
private static InputStream downloadUrl(String url) {
    if (okHttpClient == null) {
        okHttpClient = new OkHttpClient();
    }
    Request request = new Request.Builder().url(url).build();
    try {
        Response response = okHttpClient.newCall(request).execute();
        return response.body().byteStream();
    } catch (IOException e) {
        Log.e(TAG, e.toString(), e);
    }
    return null;
}
Example 100
Project: RxVolley-master  File: DownloadTest.java View source code
@Before
public void setUp() throws Exception {
    RxVolley.setRequestQueue(RequestQueue.newRequestQueue(RxVolley.CACHE_FOLDER, new OkHttpStack(new OkHttpClient())));
    callback = new HttpCallback() {

        @Override
        public void onPreStart() {
            Log.d("=====onPreStart");
        //                测试类是�行在异步的,所以此处断言会异常
        //                assertTrue(Thread.currentThread() == Looper.getMainLooper().getThread());
        }

        @Override
        public void onPreHttp() {
            super.onPreHttp();
            Log.d("=====onPreHttp");
            assertTrue(Thread.currentThread() == Looper.getMainLooper().getThread());
        }

        @Override
        public void onSuccessInAsync(byte[] t) {
            Log.d("=====onSuccessInAsync" + new String(t));
            assertNotNull(t);
            //onSuccessInAsync 一定是�行在异步
            assertFalse(Thread.currentThread() == Looper.getMainLooper().getThread());
        }

        public void onSuccess(File file) {
            Log.d("=====onSuccess" + file);
            assertTrue(Thread.currentThread() == Looper.getMainLooper().getThread());
        }

        @Override
        public void onSuccess(Map<String, String> headers, byte[] t) {
            assertNotNull(t);
            Log.d("=====onSuccessWithHeader" + headers.size() + new String(t));
            assertTrue(Thread.currentThread() == Looper.getMainLooper().getThread());
        }

        @Override
        public void onFailure(int errorNo, String strMsg) {
            super.onFailure(errorNo, strMsg);
            Log.d("=====onFailure" + strMsg);
            assertTrue(Thread.currentThread() == Looper.getMainLooper().getThread());
        }

        @Override
        public void onFinish() {
            super.onFinish();
            Log.d("=====onFinish");
            assertTrue(Thread.currentThread() == Looper.getMainLooper().getThread());
        }
    };
}
Example 101
Project: sbt-android-master  File: DataModule.java View source code
static OkHttpClient createOkHttpClient(Application app) {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, SECONDS);
    client.setReadTimeout(10, SECONDS);
    client.setWriteTimeout(10, SECONDS);
    // Install an HTTP cache in the application cache directory.
    File cacheDir = new File(app.getCacheDir(), "http");
    Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
    client.setCache(cache);
    return client;
}