Example usage for com.squareup.okhttp OkHttpClient setProxy

List of usage examples for com.squareup.okhttp OkHttpClient setProxy

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient setProxy.

Prototype

public OkHttpClient setProxy(Proxy proxy) 

Source Link

Document

Sets the HTTP proxy that will be used by connections created by this client.

Usage

From source file:org.gdg.frisbee.android.api.GapiOkTransport.java

License:Apache License

@Override
protected GapiOkHttpRequest buildRequest(String method, String url) throws IOException {
    Preconditions.checkArgument(supportsMethod(method), "HTTP method %s not supported", method);
    // connection with proxy settings
    URL connUrl = new URL(url);
    OkHttpClient client = new OkHttpClient();
    OkUrlFactory factory = new OkUrlFactory(client);
    SSLContext sslContext;/*from  w ww  . j  a va2 s. co  m*/
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, null, null);
    } catch (GeneralSecurityException e) {
        throw new AssertionError(); // The system has no TLS. Just give up.
    }
    client.setSslSocketFactory(sslContext.getSocketFactory());

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

    URLConnection conn = factory.open(connUrl);
    HttpURLConnection connection = (HttpURLConnection) conn;
    connection.setRequestMethod(method);

    return new GapiOkHttpRequest(connection);
}

From source file:org.getlantern.firetweet.extension.streaming.util.OkHttpClientImpl.java

License:Open Source License

private OkHttpClient createHttpClient(HttpClientConfiguration conf) {
    final OkHttpClient client = new OkHttpClient();
    final boolean ignoreSSLError = conf.isSSLErrorIgnored();
    if (ignoreSSLError) {
        client.setSslSocketFactory(SSLCertificateSocketFactory.getInsecure(0, null));
    } else {// w ww  .  ja v  a  2  s . c o m
        client.setSslSocketFactory(SSLCertificateSocketFactory.getDefault(0, null));
    }
    client.setSocketFactory(SocketFactory.getDefault());
    client.setConnectTimeout(conf.getHttpConnectionTimeout(), TimeUnit.MILLISECONDS);

    if (conf.isProxyConfigured()) {
        client.setProxy(new Proxy(Type.HTTP,
                InetSocketAddress.createUnresolved(conf.getHttpProxyHost(), conf.getHttpProxyPort())));
    }
    //        client.setHostnameVerifier(new HostResolvedHostnameVerifier());
    Internal.instance.setNetwork(client, new Network() {
        @Override
        public InetAddress[] resolveInetAddresses(String host) throws UnknownHostException {
            try {
                return resolver.resolve(host);
            } catch (IOException e) {
                if (e instanceof UnknownHostException)
                    throw (UnknownHostException) e;
                throw new UnknownHostException("Unable to resolve address " + e.getMessage());
            }
        }
    });
    return client;
}

From source file:org.getlantern.firetweet.util.net.OkHttpClientImpl.java

License:Open Source License

private OkHttpClient createHttpClient(HttpClientConfiguration conf) {
    final OkHttpClient client = new OkHttpClient();
    final boolean ignoreSSLError = conf.isSSLErrorIgnored();
    final SSLCertificateSocketFactory sslSocketFactory;
    if (ignoreSSLError) {
        sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getInsecure(0, null);
    } else {/* w  ww.j  av  a  2  s . co  m*/
        sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0, null);
    }
    //        sslSocketFactory.setTrustManagers(new TrustManager[]{new FiretweetTrustManager(context)});
    //        client.setHostnameVerifier(new HostResolvedHostnameVerifier(context, ignoreSSLError));
    client.setSslSocketFactory(sslSocketFactory);
    client.setSocketFactory(SocketFactory.getDefault());
    client.setConnectTimeout(conf.getHttpConnectionTimeout(), TimeUnit.MILLISECONDS);

    if (conf.isProxyConfigured()) {
        client.setProxy(new Proxy(Type.HTTP,
                InetSocketAddress.createUnresolved(conf.getHttpProxyHost(), conf.getHttpProxyPort())));
    }
    Internal.instance.setNetwork(client, new Network() {
        @Override
        public InetAddress[] resolveInetAddresses(String host) throws UnknownHostException {
            try {
                return resolver.resolve(host);
            } catch (IOException e) {
                Crashlytics.logException(e);

                if (e instanceof UnknownHostException)
                    throw (UnknownHostException) e;
                throw new UnknownHostException("Unable to resolve address " + e.getMessage());
            }
        }
    });
    return client;
}

From source file:org.graylog2.shared.bindings.providers.OkHttpClientProvider.java

License:Open Source License

@Override
public OkHttpClient get() {
    final OkHttpClient client = new OkHttpClient();
    client.setRetryOnConnectionFailure(true);
    client.setConnectTimeout(connectTimeout.getQuantity(), connectTimeout.getUnit());
    client.setWriteTimeout(writeTimeout.getQuantity(), writeTimeout.getUnit());
    client.setReadTimeout(readTimeout.getQuantity(), readTimeout.getUnit());

    if (httpProxyUri != null) {
        final Proxy proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(httpProxyUri.getHost(), httpProxyUri.getPort()));
        client.setProxy(proxy);
    }//from   w w  w . j  av  a 2 s.co m

    return client;
}

From source file:org.jclouds.http.okhttp.OkHttpCommandExecutorService.java

License:Apache License

@Override
protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException {
    OkHttpClient requestScopedClient = globalClient.clone();
    requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri()));

    Response response = requestScopedClient.newCall(nativeRequest).execute();

    HttpResponse.Builder<?> builder = HttpResponse.builder();
    builder.statusCode(response.code());
    builder.message(response.message());

    Builder<String, String> headerBuilder = ImmutableMultimap.builder();
    Headers responseHeaders = response.headers();
    for (String header : responseHeaders.names()) {
        headerBuilder.putAll(header, responseHeaders.values(header));
    }/*from  w  w  w.  ja  v  a2s . com*/

    ImmutableMultimap<String, String> headers = headerBuilder.build();

    if (response.code() == 204 && response.body() != null) {
        response.body().close();
    } else {
        Payload payload = newInputStreamPayload(response.body().byteStream());
        contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);
        builder.payload(payload);
    }

    builder.headers(filterOutContentHeaders(headers));

    return builder.build();
}

From source file:org.mariotaku.twidere.util.net.OkHttpClientImpl.java

License:Open Source License

private OkHttpClient createHttpClient(HttpClientConfiguration conf) {
    final OkHttpClient client = new OkHttpClient();
    final boolean ignoreSSLError = conf.isSSLErrorIgnored();
    final SSLCertificateSocketFactory sslSocketFactory;
    if (ignoreSSLError) {
        sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getInsecure(0, null);
    } else {//from   w  w  w  .j  av  a  2s . com
        sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0, null);
    }
    //        sslSocketFactory.setTrustManagers(new TrustManager[]{new TwidereTrustManager(context)});
    //        client.setHostnameVerifier(new HostResolvedHostnameVerifier(context, ignoreSSLError));
    client.setSslSocketFactory(sslSocketFactory);
    client.setSocketFactory(SocketFactory.getDefault());
    client.setConnectTimeout(conf.getHttpConnectionTimeout(), TimeUnit.MILLISECONDS);

    if (conf.isProxyConfigured()) {
        client.setProxy(new Proxy(Type.HTTP,
                InetSocketAddress.createUnresolved(conf.getHttpProxyHost(), conf.getHttpProxyPort())));
    }
    Internal.instance.setNetwork(client, new Network() {
        @Override
        public InetAddress[] resolveInetAddresses(String host) throws UnknownHostException {
            try {
                return resolver.resolve(host);
            } catch (IOException e) {
                if (e instanceof UnknownHostException)
                    throw (UnknownHostException) e;
                throw new UnknownHostException("Unable to resolve address " + e.getMessage());
            }
        }
    });
    return client;
}

From source file:org.sufficientlysecure.keychain.keyimport.FacebookKeyserver.java

License:Open Source License

private String query(String fbUsername) throws QueryFailedException {
    try {/*from  w w  w  . ja va 2  s .  c o  m*/
        String request = String.format(FB_KEY_URL_FORMAT, fbUsername);
        Log.d(Constants.TAG, "fetching from Facebook with: " + request + " proxy: " + mProxy);

        OkHttpClient client = new OkHttpClient();
        client.setProxy(mProxy);

        URL url = new URL(request);

        Response response = client.newCall(new Request.Builder().url(url).build()).execute();

        // contains body both in case of success or failure
        String responseBody = response.body().string();

        if (response.isSuccessful()) {
            return responseBody;
        } else {
            // probably a 404 indicating that the key does not exist
            throw new QueryFailedException("key for " + fbUsername + " not found on Facebook");
        }

    } catch (IOException e) {
        Log.e(Constants.TAG, "IOException at Facebook key download", e);
        throw new QueryFailedException("Cannot connect to Facebook. " + "Check your Internet connection!"
                + (mProxy == Proxy.NO_PROXY ? "" : " Using proxy " + mProxy));
    }
}

From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyserver.java

License:Apache License

/**
 * returns a client with pinned certificate if necessary
 *
 * @param url   url to be queried by client
 * @param proxy proxy to be used by client
 * @return client with a pinned certificate if necessary
 *//*from   w ww . j  a  v  a 2s. c  o  m*/
public static OkHttpClient getClient(URL url, Proxy proxy) throws IOException {
    OkHttpClient client = new OkHttpClient();

    try {
        TlsHelper.usePinnedCertificateIfAvailable(client, url);
    } catch (TlsHelper.TlsHelperException e) {
        Log.w(Constants.TAG, e);
    }

    // don't follow any redirects
    client.setFollowRedirects(false);
    client.setFollowSslRedirects(false);

    if (proxy != null) {
        client.setProxy(proxy);
        client.setConnectTimeout(30000, TimeUnit.MILLISECONDS);
    } else {
        client.setProxy(Proxy.NO_PROXY);
        client.setConnectTimeout(5000, TimeUnit.MILLISECONDS);
    }
    client.setReadTimeout(45000, TimeUnit.MILLISECONDS);

    return client;
}

From source file:org.wso2.carbon.identity.authenticator.duo.DuoHttp.java

License:Open Source License

public Response executeHttpRequest() throws Exception {
    String url = "https://" + host + uri;
    String queryString = createQueryString();
    Request.Builder builder = new Request.Builder();
    if (method.equals("POST")) {
        builder.post(RequestBody.create(FORM_ENCODED, queryString));
    } else if (method.equals("PUT")) {
        builder.put(RequestBody.create(FORM_ENCODED, queryString));
    } else if (method.equals("GET")) {
        if (queryString.length() > 0) {
            url += "?" + queryString;
        }//from  w w  w. j a v a 2 s  . c om
        builder.get();
    } else if (method.equals("DELETE")) {
        if (queryString.length() > 0) {
            url += "?" + queryString;
        }
        builder.delete();
    } else {
        throw new UnsupportedOperationException("Unsupported method: " + method);
    }
    Request request = builder.url(url).build();
    // Set up client.
    OkHttpClient httpclient = new OkHttpClient();
    if (proxy != null) {
        httpclient.setProxy(proxy);
    }
    httpclient.setConnectTimeout(timeout, TimeUnit.SECONDS);
    httpclient.setWriteTimeout(timeout, TimeUnit.SECONDS);
    httpclient.setReadTimeout(timeout, TimeUnit.SECONDS);
    // finish and execute request
    builder.headers(headers.build());
    return httpclient.newCall(builder.build()).execute();
}