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.andrew67.ddrfinder.adapters.MapLoaderV3.java

License:Open Source License

@Override
protected ApiResult doInBackground(LatLngBounds... boxes) {
    ApiResult result = null;// w  w w  .  j  a  va 2 s.  c  o m
    try {
        if (boxes.length == 0)
            throw new IllegalArgumentException("No boxes passed to doInBackground");
        final LatLngBounds box = boxes[0];

        String datasrc = sharedPref.getString(SettingsActivity.KEY_PREF_API_SRC, "");
        if (SettingsActivity.API_SRC_CUSTOM.equals(datasrc)) {
            datasrc = sharedPref.getString(SettingsActivity.KEY_PREF_API_SRC_CUSTOM, "");
        }

        final OkHttpClient client = new OkHttpClient();
        final String LOADER_API_URL = sharedPref.getString(SettingsActivity.KEY_PREF_API_URL, "");
        final HttpUrl requestURL = HttpUrl.parse(LOADER_API_URL).newBuilder()
                .addQueryParameter("version", "" + SettingsActivity.API_V30)
                .addQueryParameter("datasrc", datasrc)
                .addQueryParameter("latupper", "" + box.northeast.latitude)
                .addQueryParameter("lngupper", "" + box.northeast.longitude)
                .addQueryParameter("latlower", "" + box.southwest.latitude)
                .addQueryParameter("lnglower", "" + box.southwest.longitude).build();

        Log.d("api", "Request URL: " + requestURL);
        final Request get = new Request.Builder().header("User-Agent", BuildConfig.APPLICATION_ID + " "
                + BuildConfig.VERSION_NAME + "/Android?SDK=" + Build.VERSION.SDK_INT).url(requestURL).build();

        final Response response = client.newCall(get).execute();
        final int statusCode = response.code();
        Log.d("api", "Status code: " + statusCode);

        // Data/error loaded OK
        if (statusCode == 200 || statusCode == 400) {
            final Gson gson = new Gson();
            result = gson.fromJson(response.body().charStream(), Result.class);
            result.setBounds(box);
            Log.d("api", "Raw API result: " + gson.toJson(result, Result.class));
        }
        // Unexpected error code
        else {
            throw new RuntimeException("Unexpected HTTP status code: " + statusCode);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.android.cloudfiles.cloudfilesforandroid.CloudFiles.java

License:Apache License

private CloudFiles() {
    client = new OkHttpClient();
}

From source file:com.android.mms.service_alt.MmsHttpClient.java

License:Apache License

/**
 * Open an HTTP connection//from  ww  w  . j a v a  2  s. c o m
 *
 * TODO: The following code is borrowed from android.net.Network.openConnection
 * Once that method supports proxy, we should use that instead
 * Also we should remove the associated HostResolver and ConnectionPool from
 * MmsNetworkManager
 *
 * @param url The URL to connect to
 * @param proxy The proxy to use
 * @return The opened HttpURLConnection
 * @throws MalformedURLException If URL is malformed
 */
private HttpURLConnection openConnection(URL url, final Proxy proxy) throws MalformedURLException {
    final String protocol = url.getProtocol();
    OkHttpClient okHttpClient;
    if (protocol.equals("http")) {
        okHttpClient = new OkHttpClient();
        okHttpClient.setFollowRedirects(false);
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        okHttpClient.setProxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                if (proxy != null) {
                    return Arrays.asList(proxy);
                } else {
                    return new ArrayList<Proxy>();
                }
            }

            @Override
            public void connectFailed(URI uri, SocketAddress address, IOException failure) {

            }
        });
        okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
        okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
        okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
        okHttpClient.setSocketFactory(SocketFactory.getDefault());
        Internal.instance.setNetwork(okHttpClient, mHostResolver);

        if (proxy != null) {
            okHttpClient.setProxy(proxy);
        }

        return new HttpURLConnectionImpl(url, okHttpClient);
    } else if (protocol.equals("https")) {
        okHttpClient = new OkHttpClient();
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
        okHttpClient.setHostnameVerifier(verifier);
        okHttpClient.setSslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory());
        okHttpClient.setProxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                return Arrays.asList(proxy);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress address, IOException failure) {

            }
        });
        okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
        okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
        okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
        Internal.instance.setNetwork(okHttpClient, mHostResolver);

        return new HttpsURLConnectionImpl(url, okHttpClient);
    } else {
        throw new MalformedURLException("Invalid URL or unrecognized protocol " + protocol);
    }
}

From source file:com.androidzeitgeist.dashwatch.common.IOUtil.java

License:Apache License

public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring)
        throws OpenUriException {

    if (uri == null) {
        throw new IllegalArgumentException("Uri cannot be empty");
    }/* www  . j a va2s .  co  m*/

    String scheme = uri.getScheme();
    if (scheme == null) {
        throw new OpenUriException(false, new IOException("Uri had no scheme"));
    }

    InputStream in = null;
    if ("content".equals(scheme)) {
        try {
            in = context.getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            throw new OpenUriException(false, e);
        } catch (SecurityException e) {
            throw new OpenUriException(false, e);
        }

    } else if ("file".equals(scheme)) {
        List<String> segments = uri.getPathSegments();
        if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) {
            AssetManager assetManager = context.getAssets();
            StringBuilder assetPath = new StringBuilder();
            for (int i = 1; i < segments.size(); i++) {
                if (i > 1) {
                    assetPath.append("/");
                }
                assetPath.append(segments.get(i));
            }
            try {
                in = assetManager.open(assetPath.toString());
            } catch (IOException e) {
                throw new OpenUriException(false, e);
            }
        } else {
            try {
                in = new FileInputStream(new File(uri.getPath()));
            } catch (FileNotFoundException e) {
                throw new OpenUriException(false, e);
            }
        }

    } else if ("http".equals(scheme) || "https".equals(scheme)) {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = null;
        int responseCode = 0;
        String responseMessage = null;
        try {
            conn = client.open(new URL(uri.toString()));
            conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
            responseCode = conn.getResponseCode();
            responseMessage = conn.getResponseMessage();
            if (!(responseCode >= 200 && responseCode < 300)) {
                throw new IOException("HTTP error response.");
            }
            if (reqContentTypeSubstring != null) {
                String contentType = conn.getContentType();
                if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) {
                    throw new IOException("HTTP content type '" + contentType + "' didn't match '"
                            + reqContentTypeSubstring + "'.");
                }
            }
            in = conn.getInputStream();

        } catch (MalformedURLException e) {
            throw new OpenUriException(false, e);
        } catch (IOException e) {
            if (conn != null && responseCode > 0) {
                throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e);
            } else {
                throw new OpenUriException(false, e);
            }

        }
    }

    return in;
}

From source file:com.androidzeitgeist.dashwatch.common.IOUtil.java

License:Apache License

static String fetchPlainText(URL url) throws IOException {
    InputStream in = null;//w w  w.j  a va  2 s . c  o m

    try {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = client.open(url);
        conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
        conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
        in = conn.getInputStream();
        return readFullyPlainText(in);

    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.animedetour.android.framework.dependencyinjection.module.NetworkModule.java

License:Open Source License

@Provides
@Singleton
public OkHttpClient okHttp(Cache cache) {
    OkHttpClient client = new OkHttpClient();
    client.setCache(cache);

    return client;
}

From source file:com.anony.okhttp.sample.CacheResponse.java

License:Apache License

public CacheResponse(File cacheDirectory) throws Exception {
    int cacheSize = 10 * 1024 * 1024; // 10 MiB
    Cache cache = new Cache(cacheDirectory, cacheSize);

    client = new OkHttpClient();
    client.setCache(cache);//  w  w  w .ja v a  2s . c o  m
}

From source file:com.anony.okhttp.sample.CertificatePinning.java

License:Apache License

public CertificatePinning() {
    client = new OkHttpClient();
    client.setCertificatePinner(//from  w w w  .  jav a 2 s  . c o m
            new CertificatePinner.Builder().add("publicobject.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=")
                    .add("publicobject.com", "sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=")
                    .add("publicobject.com", "sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=")
                    .add("publicobject.com", "sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=").build());
}

From source file:com.anony.okhttp.sample.ConfigureTimeouts.java

License:Apache License

public ConfigureTimeouts() throws Exception {
    client = new OkHttpClient();
    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setWriteTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
}

From source file:com.anony.okhttp.sample.CustomTrust.java

License:Apache License

public CustomTrust() {
    client = new OkHttpClient();
    SSLContext sslContext = sslContextForTrustedCertificates(trustedCertificatesInputStream());
    client.setSslSocketFactory(sslContext.getSocketFactory());
}