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.wialon.remote.OkSdkHttpClient.java

License:Apache License

public OkHttpClient getHttpClient(int timeout) {
    if ((timeout == 0 || timeout == DEFAULT_SOCKET_TIMEOUT) && defaultClient != null)
        return defaultClient;
    else {//  w ww. j a  v a  2 s  .  c o m
        OkHttpClient client = new OkHttpClient();
        timeout = timeout == 0 ? DEFAULT_SOCKET_TIMEOUT : timeout;
        client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
        client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);
        client.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
        return client;
    }
}

From source file:com.windigo.http.client.OkClient.java

License:Apache License

private static OkHttpClient generateDefaultOkHttp() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(GlobalSettings.CONNNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
    client.setReadTimeout(GlobalSettings.CONNECTION_READ_TIMEOUT, TimeUnit.MILLISECONDS);
    return client;
}

From source file:com.xebia.xsdnl.innorater.server.Servers.java

License:Creative Commons License

public static RaterService raterService() {
    if (raterService == null) {
        OkHttpClient okHttpClient = new OkHttpClient();

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

        final String userAgent = buildUserAgent();
        RequestInterceptor standardHeaders = new RequestInterceptor() {
            @Override// w  w  w.ja va2 s.  c o  m
            public void intercept(RequestFacade request) {
                // For response compression, AppEngine requires the Accept-Encoding header that
                // OkHTTP adds automatically *and* the string "gzip" as part of the User-Agent.
                request.addHeader("User-Agent", userAgent);
                request.addHeader("Accept", "application/json");
            }
        };

        RestAdapter restAdapter = new RestAdapter.Builder().setClient(new OkClient(okHttpClient))
                .setEndpoint("https://xebia-innovation-day-rater.appspot.com")
                .setLogLevel(RestAdapter.LogLevel.FULL).setConverter(new GsonConverter(gson))
                .setRequestInterceptor(standardHeaders).build();

        raterService = restAdapter.create(RaterService.class);
    }
    return raterService;
}

From source file:com.xing.android.sdk.network.DefaultUrlFactory.java

License:Open Source License

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

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@SuppressWarnings("unchecked")
@Test//from w w w.  j a  v  a2s . co  m
public void specHandlesRequestBuildFailure() throws Exception {
    XingApi failingApi = new XingApi.Builder().loggedOut().apiEndpoint(httpUrl).client(new OkHttpClient() {
        @Override
        public Call newCall(Request request) {
            throw new UnsupportedOperationException("I'm broken!");
        }
    }).build();

    CallSpec spec = new CallSpec.Builder(failingApi, HttpMethod.GET, "/", false).responseAs(Object.class)
            .build();

    final AtomicReference<Throwable> responseRef = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    spec.enqueue(new Callback<Object, Object>() {
        @Override
        public void onResponse(Response<Object, Object> response) {
            fail("unexpected #onSuccess() call");
        }

        @Override
        public void onFailure(Throwable t) {
            responseRef.set(t);
            latch.countDown();
        }
    });

    latch.await(2, TimeUnit.SECONDS);
    assertThat(responseRef.get()).isInstanceOf(UnsupportedOperationException.class).hasMessage("I'm broken!");
}

From source file:com.xjeffrose.xio2.http.server.FileHandlerTest.java

License:Apache License

@Test
public void testHandle() throws Exception {
    Server s = Http.newServer();// w  ww.j  av  a 2 s . c  o m
    s.bind(9012, new FileHandler("src/test/resources"));
    s.serve();

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url("http://localhost:9012/test.txt").build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);

    assertTrue(response.isSuccessful());
    assertEquals(response.code(), 200);
    assertEquals("this is a test.txt", response.body().string());
}

From source file:com.xjeffrose.xio2.http.server.ServerTest.java

License:Apache License

private OkHttpClient getUnsafeOkHttpClient() {
    try {/* www .jav  a  2s  .co  m*/
        // 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("TLSv1.2");
        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);
    }
}

From source file:com.yandex.disk.rest.OkHttpClientFactory.java

License:Apache License

public static OkHttpClient makeClient() {
    OkHttpClient client = new OkHttpClient();

    client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);

    client.setFollowSslRedirects(true);/*from  w w w . java2 s  .  com*/
    client.setFollowRedirects(true);

    return client;
}

From source file:com.yandex.money.test.processes.ShowcaseProcessTest.java

License:Open Source License

private static ApiClient getClientByHost(final String host) {
    return new ApiClient() {
        @Override//from ww  w  .j a  v a  2  s .co m
        public String getClientId() {
            return null;
        }

        @Override
        public OkHttpClient getHttpClient() {
            final OkHttpClient client = new OkHttpClient();
            client.setFollowRedirects(false);
            return client;
        }

        @Override
        public HostsProvider getHostsProvider() {
            return getHostsProviderByString(host);
        }

        @Override
        public UserAgent getUserAgent() {
            return null;
        }

        @Override
        public Language getLanguage() {
            return Language.RUSSIAN;
        }
    };
}

From source file:com.yetanotherdevblog.rottentomatoes.api.RottenTomatoes.java

License:Apache License

/**
 * Return the current {@link retrofit.RestAdapter} instance. If none exists (first call, API key changed),
 * builds a new one.//  w w  w  .  j  a  v a2 s . c o m
 * <p>
 * When building, sets the endpoint, a custom converter ({@link RottenTomatoesHelper#getGsonBuilder()})
 * and a {@link retrofit.RequestInterceptor} which adds the API key as query param.
 */
protected RestAdapter getRestAdapter() {
    if (restAdapter == null) {
        RestAdapter.Builder builder = newRestAdapterBuilder();

        builder.setEndpoint(API_URL);
        builder.setConverter(new GsonConverter(RottenTomatoesHelper.getGsonBuilder().create()));
        builder.setRequestInterceptor(new RequestInterceptor() {
            public void intercept(RequestFacade requestFacade) {
                requestFacade.addQueryParam(PARAM_API_KEY, apiKey);
            }
        });

        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(10, TimeUnit.SECONDS);
        client.setReadTimeout(10, TimeUnit.SECONDS);
        client.setWriteTimeout(10, TimeUnit.SECONDS);
        builder.setClient(new OkClient(client));

        if (isDebug) {
            builder.setLogLevel(RestAdapter.LogLevel.FULL);
        }

        restAdapter = builder.build();
    }

    return restAdapter;
}