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:io.apiman.gateway.engine.prometheus.BasicMetricsTest.java

License:Apache License

@Before
public void before() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    client = new OkHttpClient();

    Map<String, String> promConfig = new HashMap<>();
    promConfig.put("port", "9876");
    this.prometheusMetrics = new PrometheusScrapeMetrics(promConfig, result -> latch.countDown());
    prometheusMetrics.setComponentRegistry(null);

    latch.await();//from   w  ww  . j  a va2  s  . c om
}

From source file:io.apiman.gateway.platforms.servlet.connectors.HttpConnectorFactory.java

License:Apache License

/**
 * @return a new http client//from  w  w w  .  j a va2  s .c  om
 */
private OkHttpClient createHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(connectorOptions.getReadTimeout(), TimeUnit.SECONDS);
    client.setWriteTimeout(connectorOptions.getWriteTimeout(), TimeUnit.SECONDS);
    client.setConnectTimeout(connectorOptions.getConnectTimeout(), TimeUnit.SECONDS);
    client.setFollowRedirects(connectorOptions.isFollowRedirects());
    client.setFollowSslRedirects(connectorOptions.isFollowRedirects());
    client.setProxySelector(ProxySelector.getDefault());
    client.setCookieHandler(CookieHandler.getDefault());
    client.setCertificatePinner(CertificatePinner.DEFAULT);
    client.setAuthenticator(AuthenticatorAdapter.INSTANCE);
    client.setConnectionPool(ConnectionPool.getDefault());
    client.setProtocols(Util.immutableList(Protocol.HTTP_1_1));
    client.setConnectionSpecs(DEFAULT_CONNECTION_SPECS);
    client.setSocketFactory(SocketFactory.getDefault());
    Internal.instance.setNetwork(client, Network.DEFAULT);

    return client;
}

From source file:io.authme.sdk.server.PostData.java

License:Apache License

public PostData(Callback callback, String apiKey) {
    this.callback = callback;
    client = new OkHttpClient();
    client.setConnectTimeout(5, TimeUnit.MINUTES);
    client.setReadTimeout(5, TimeUnit.MINUTES);
    client.setWriteTimeout(5, TimeUnit.MINUTES);
    this.apiKey = apiKey;
}

From source file:io.bitfactory.mobileclimatemonitor.SlackReporter.java

License:Apache License

@Background
protected void sendValuesToSlack() {

    if (temperatureValue == 0) {
        return;//w w  w  .j  ava 2s. co  m
    }

    if (humidityValue == 0) {
        return;
    }

    try {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("text",
                Helper.formatTemperature(temperatureValue) + "\n" + Helper.formatHumidity(humidityValue));
        jsonObject.put("channel", slackChannel);
        jsonObject.put("username", slackSenderName);
        jsonObject.put("icon_emoji", ":cubimal_chick:");

        MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

        Request request = new Request.Builder().url(new URL(slackWebhookUrl))
                .post(RequestBody.create(MEDIA_TYPE_JSON, jsonObject.toString())).build();

        new OkHttpClient().newCall(request).execute();

    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }

    temperatureValue = 0;
    humidityValue = 0;
}

From source file:io.fabric8.devops.connector.DevOpsConnector.java

License:Apache License

protected void createGerritRepo(String repoName, String gerritUser, String gerritPwd,
        String gerritGitInitialCommit, String gerritGitRepoDescription) throws Exception {

    // lets add defaults if not env vars
    final String username = Strings.isNullOrBlank(gerritUser) ? "admin" : gerritUser;
    final String password = Strings.isNullOrBlank(gerritPwd) ? "secret" : gerritPwd;

    log.info("A Gerrit git repo will be created for this name : " + repoName);

    String gerritAddress = KubernetesHelper.getServiceURL(kubernetes, ServiceNames.GERRIT, namespace, "http",
            true);//  w ww  .  j av a 2 s .com
    log.info("Found gerrit address: " + gerritAddress + " for namespace: " + namespace
            + " on Kubernetes address: " + kubernetes.getMasterUrl());

    if (Strings.isNullOrBlank(gerritAddress)) {
        throw new Exception("No address for service " + ServiceNames.GERRIT + " in namespace: " + namespace
                + " on Kubernetes address: " + kubernetes.getMasterUrl());
    }

    String GERRIT_URL = gerritAddress + "/a/projects/" + repoName;

    OkHttpClient client = new OkHttpClient();
    if (isNotNullOrEmpty(gerritUser) && isNotNullOrEmpty(gerritPwd)) {
        client.setAuthenticator(new Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                List<Challenge> challenges = response.challenges();
                Request request = response.request();
                for (int i = 0, size = challenges.size(); i < size; i++) {
                    Challenge challenge = challenges.get(i);
                    if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                        continue;

                    String credential = Credentials.basic(username, password);
                    return request.newBuilder().header("Authorization", credential).build();
                }
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
    }

    System.out.println("Requesting : " + GERRIT_URL);

    try {
        CreateRepositoryDTO createRepoDTO = new CreateRepositoryDTO();
        createRepoDTO.setDescription(gerritGitRepoDescription);
        createRepoDTO.setName(repoName);
        createRepoDTO.setCreate_empty_commit(Boolean.valueOf(gerritGitInitialCommit));

        RequestBody body = RequestBody.create(JSON, MAPPER.writeValueAsString(createRepoDTO));
        Request request = new Request.Builder().post(body).url(GERRIT_URL).build();
        Response response = client.newCall(request).execute();
        System.out.println("responseBody : " + response.body().string());

    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (client != null && client.getConnectionPool() != null) {
            client.getConnectionPool().evictAll();
        }
    }
}

From source file:io.fabric8.docker.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {/*w  w  w  .jav  a  2s.c  om*/
        OkHttpClient httpClient = new OkHttpClient();

        httpClient.setConnectionPool(ConnectionPool.getDefault());
        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        if (usesUnixSocket(config)) {
            URL masterURL = new URL(config.getDockerUrl().replaceFirst(UNIX_SCHEME, FILE_SCHEME));
            httpClient.setSocketFactory(new UnixSocketFactory(masterURL.getFile()));
            config.setDockerUrl(UNIX_FAKE_URL);
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    for (int i = 0, size = challenges.size(); i < size; i++) {
                        Challenge challenge = challenges.get(i);
                        if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                            continue;

                        String credential = Credentials.basic(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getDockerUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getDockerUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new DockerClientException("Invalid proxy server configuration", e);
            }
        }

        return httpClient;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.kubernetes.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {/*from w ww .ja v a2  s. c  o  m*/
        OkHttpClient httpClient = new OkHttpClient();

        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    for (int i = 0, size = challenges.size(); i < size; i++) {
                        Challenge challenge = challenges.get(i);
                        if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                            continue;

                        String credential = Credentials.basic(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getMasterUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getMasterUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new KubernetesClientException("Invalid proxy server configuration", e);
            }
        }

        if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) {
            httpClient.networkInterceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent())
                            .build();
                    return chain.proceed(agent);
                }
            });
        }

        return httpClient;
    } catch (Exception e) {
        throw KubernetesClientException.launderThrowable(e);
    }
}

From source file:io.github.baoliandeng.core.LocalVpnService.java

License:Open Source License

@Override
public synchronized void run() {
    try {/*from   ww w  .  j  a v  a 2 s.com*/
        Log.d(Constant.TAG, "VPNService work thread is running... " + ID);

        ProxyConfig.AppInstallID = getAppInstallID();
        ProxyConfig.AppVersion = getVersionName();
        writeLog("Android version: %s", Build.VERSION.RELEASE);
        writeLog("App version: %s", ProxyConfig.AppVersion);

        waitUntilPreapred();

        Client.Provider.Stub stub = new Client.Provider.Stub() {
            public boolean Verbose() {
                return ProxyConfig.IS_DEBUG;
            }

            public String Model() {
                return model;
            }

            public String Device() {
                return device;
            }

            public String Version() {
                return version;
            }

            public String AppName() {
                return "Lantern";
            }

            public String SettingsDir() {
                return getFilesDir().getPath();
            }

            public void Protect(long fd) {
                protect((int) fd);
            }
        };

        Client.Configure(stub);
        Client.Start(stub);

        ChinaIpMaskManager.loadFromFile(getResources().openRawResource(R.raw.ipmask));

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("https://myhosts.sinaapp.com/blacklist.txt").build();

        try {
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            m_Blacklist = body.split("\\r?\\n");
        } catch (IOException e) {
            Log.e(Constant.TAG, "Unable to fetch blacklist");
        }

        runVPN();

    } catch (InterruptedException e) {
        Log.e(Constant.TAG, "Exception", e);
    } catch (Exception e) {
        e.printStackTrace();
        writeLog("Fatal error: %s", e.toString());
    }

    writeLog("BaoLianDeng terminated.");
    dispose();
}

From source file:io.github.hidroh.materialistic.ActivityModule.java

License:Apache License

@Provides
@Singleton
public UserServices provideUserServices() {
    return new UserServicesClient(new OkHttpClient());
}

From source file:io.jawg.osmcontributor.flickr.util.FlickrPhotoUtils.java

License:Open Source License

public static RestAdapter getAdapter() {
    if (adapter == null) {
        OkHttpClient okHttpClient = new OkHttpClient();
        try {//  w  w  w.  ja va2s  .com
            SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(
                    new URL("https://api.flickr.com/services/rest"));
            okHttpClient.setSslSocketFactory(NoSSLv3Factory);
            adapter = new RestAdapter.Builder().setConverter(new StringConverter())
                    .setEndpoint("https://api.flickr.com/services").setClient(new OkClient(okHttpClient))
                    .setLogLevel(RestAdapter.LogLevel.FULL).setLog(new AndroidLog("---------------------->"))
                    .build();
        } catch (MalformedURLException e) {

        } catch (IOException e) {

        }
    }
    return adapter;
}