List of usage examples for com.squareup.okhttp OkHttpClient setFollowSslRedirects
public OkHttpClient setFollowSslRedirects(boolean followProtocolRedirects)
From source file:com.frostwire.http.HttpClient.java
License:Open Source License
private static OkHttpClient buildDefaultClient() { OkHttpClient c = new OkHttpClient(); c.setFollowRedirects(true);//from w ww .ja v a2s . com c.setFollowSslRedirects(true); c.setConnectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); c.setReadTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); c.setWriteTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); c.setHostnameVerifier(buildHostnameVerifier()); c.setSslSocketFactory(buildSSLSocketFactory()); c.interceptors().add(new GzipInterceptor()); return c; }
From source file:com.groupon.odo.bmp.BrowserMobProxyHandler.java
License:Apache License
protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException { try {//from w w w .j a va 2 s .c o m String urlStr = url.toString(); if (urlStr.toLowerCase().startsWith(Constants.ODO_INTERNAL_WEBAPP_URL)) { urlStr = "http://localhost:" + com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT) + "/odo"; } // setup okhttp to ignore ssl issues OkHttpClient okHttpClient = getUnsafeOkHttpClient(); okHttpClient.setFollowRedirects(false); okHttpClient.setFollowSslRedirects(false); Request.Builder okRequestBuilder = new Request.Builder(); /* * urlStr.indexOf(":") == urlStr.lastIndexOf(":") verifies that the url does not have a port * by checking it only has a : as part of http:// */ if (urlStr.startsWith("http://") && urlStr.indexOf(":") == urlStr.lastIndexOf(":")) { int httpPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT); urlStr = urlStr.replace(getHostNameFromURL(urlStr), localIP + ":" + httpPort); } okRequestBuilder = okRequestBuilder.url(urlStr); // copy request headers Enumeration<?> enm = request.getFieldNames(); boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; boolean usedContentLength = false; long contentLength = 0; while (enm.hasMoreElements()) { String hdr = (String) enm.nextElement(); if (!isGet && HttpFields.__ContentType.equals(hdr)) { hasContent = true; } if (!isGet && HttpFields.__ContentLength.equals(hdr)) { contentLength = Long.parseLong(request.getField(hdr)); usedContentLength = true; } Enumeration<?> vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } if (!_DontProxyHeaders.containsKey(hdr)) { okRequestBuilder = okRequestBuilder.addHeader(hdr, val); //httpReq.addRequestHeader(hdr, val); } } } } if ("GET".equals(request.getMethod())) { // don't need to do anything else } else if ("POST".equals(request.getMethod()) || "PUT".equals(request.getMethod()) || "DELETE".equals(request.getMethod())) { RequestBody okRequestBody = null; if (hasContent) { final String contentType = request.getContentType(); final byte[] bytes = IOUtils.toByteArray(request.getInputStream()); okRequestBody = new RequestBody() { @Override public MediaType contentType() { MediaType.parse(contentType); return null; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { bufferedSink.write(bytes); } }; // we need to add some ODO specific headers to give ODO a hint for content-length vs transfer-encoding // since okHTTP will automatically chunk even if the request was not chunked // this allows Odo to set the appropriate headers when the server request is made if (usedContentLength) { okRequestBuilder = okRequestBuilder.addHeader("ODO-POST-TYPE", "content-length:" + contentLength); } } else { okRequestBody = RequestBody.create(null, new byte[0]); } if ("POST".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.post(okRequestBody); } else if ("PUT".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.put(okRequestBody); } else if ("DELETE".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.delete(okRequestBody); } } else if ("OPTIONS".equals(request.getMethod())) { // NOT SUPPORTED } else if ("HEAD".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.head(); } else { LOG.warn("Unexpected request method %s, giving up", request.getMethod()); request.setHandled(true); return -1; } Request okRequest = okRequestBuilder.build(); Response okResponse = okHttpClient.newCall(okRequest).execute(); // Set status and response message response.setStatus(okResponse.code()); response.setReason(okResponse.message()); // copy response headers for (int headerNum = 0; headerNum < okResponse.headers().size(); headerNum++) { String headerName = okResponse.headers().name(headerNum); if (!_DontProxyHeaders.containsKey(headerName) && !_ProxyAuthHeaders.containsKey(headerName)) { response.addField(headerName, okResponse.headers().value(headerNum)); } } // write output to response output stream try { IOUtils.copy(okResponse.body().byteStream(), response.getOutputStream()); } catch (Exception e) { // ignoring this until we refactor the proxy // The copy occasionally fails due to an issue where okResponse has more data in the body than it's supposed to // The client still gets all of the data it was expecting } request.setHandled(true); return okResponse.body().contentLength(); } catch (Exception e) { LOG.warn("Caught exception proxying: ", e); reportError(e, url, response); request.setHandled(true); return -1; } }
From source file:com.lobobrowser.LoboBrowser.java
License:Open Source License
/** * Initializes the global URLStreamHandlerFactory. * <p>// w w w .ja v a2 s . c om * This method is invoked by {@link #init(boolean, boolean)}. */ public static void initProtocols(final SSLSocketFactory sslSocketFactory) { // Configure URL protocol handlers final PlatformStreamHandlerFactory factory = PlatformStreamHandlerFactory.getInstance(); URL.setURLStreamHandlerFactory(factory); final OkHttpClient okHttpClient = new OkHttpClient(); final ArrayList<Protocol> protocolList = new ArrayList<>(2); protocolList.add(Protocol.HTTP_1_1); protocolList.add(Protocol.HTTP_2); okHttpClient.setProtocols(protocolList); okHttpClient.setConnectTimeout(100, TimeUnit.SECONDS); // HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory); okHttpClient.setSslSocketFactory(sslSocketFactory); okHttpClient.setFollowRedirects(false); okHttpClient.setFollowSslRedirects(false); factory.addFactory(new OkUrlFactory(okHttpClient)); factory.addFactory(new LocalStreamHandlerFactory()); }
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); client.setFollowRedirects(true);/* w ww. ja va 2 s . c om*/ return client; }
From source file:io.apiman.gateway.platforms.servlet.connectors.HttpConnectorFactory.java
License:Apache License
/** * @return a new http client/*w ww . ja v a 2 s.c o m*/ */ 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.fabric8.docker.client.utils.HttpClientUtils.java
License:Apache License
public static OkHttpClient createHttpClient(final Config config) { try {// w w w .j a v a 2s .c o m 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 w w . jav a 2 s . co 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: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 w w . j a va2 s . com 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.sufficientlysecure.keychain.ui.dialog.AddEditKeyserverDialogFragment.java
License:Open Source License
public void verifyConnection(String keyserver, final Proxy proxy, final boolean onlyTrustedKeyserver) { new AsyncTask<String, Void, FailureReason>() { ProgressDialog mProgressDialog;//from w w w . jav a 2s . c om String mKeyserver; @Override protected void onPreExecute() { mProgressDialog = new ProgressDialog(getActivity()); mProgressDialog.setMessage(getString(R.string.progress_verifying_keyserver_connection)); mProgressDialog.setCancelable(false); mProgressDialog.show(); } @Override protected FailureReason doInBackground(String... keyservers) { mKeyserver = keyservers[0]; FailureReason reason = null; try { // replace hkps/hkp scheme and reconstruct Uri Uri keyserverUri = Uri.parse(mKeyserver); String scheme = keyserverUri.getScheme(); String schemeSpecificPart = keyserverUri.getSchemeSpecificPart(); String fragment = keyserverUri.getFragment(); if (scheme == null) { throw new MalformedURLException(); } if ("hkps".equalsIgnoreCase(scheme)) { scheme = "https"; } else if ("hkp".equalsIgnoreCase(scheme)) { scheme = "http"; } URI newKeyserver = new URI(scheme, schemeSpecificPart, fragment); Log.d("Converted URL", newKeyserver.toString()); OkHttpClient client = HkpKeyserver.getClient(newKeyserver.toURL(), proxy); // don't follow any redirects client.setFollowRedirects(false); client.setFollowSslRedirects(false); if (onlyTrustedKeyserver && !TlsHelper.usePinnedCertificateIfAvailable(client, newKeyserver.toURL())) { Log.w(Constants.TAG, "No pinned certificate for this host in OpenKeychain's assets."); reason = FailureReason.NO_PINNED_CERTIFICATE; return reason; } client.newCall(new Request.Builder().url(newKeyserver.toURL()).build()).execute(); } catch (TlsHelper.TlsHelperException e) { reason = FailureReason.CONNECTION_FAILED; } catch (MalformedURLException | URISyntaxException e) { Log.w(Constants.TAG, "Invalid keyserver URL entered by user."); reason = FailureReason.INVALID_URL; } catch (IOException e) { Log.w(Constants.TAG, "Could not connect to entered keyserver url"); reason = FailureReason.CONNECTION_FAILED; } return reason; } @Override protected void onPostExecute(FailureReason failureReason) { mProgressDialog.dismiss(); if (failureReason == null) { keyserverEdited(mKeyserver, true); } else { verificationFailed(failureReason); } } }.execute(keyserver); }
From source file:ti.okhttp.TiOkhttpclient.java
License:Open Source License
protected void setUpClient(OkHttpClient client) { client.setFollowRedirects(autoRedirect); client.setFollowSslRedirects(autoRedirect); }