List of usage examples for com.squareup.okhttp OkHttpClient setFollowRedirects
public void setFollowRedirects(boolean followRedirects)
From source file:com.tinspx.util.net.okhttp.OkHttpContext.java
License:Open Source License
private OkHttpContext(@NonNull OkHttpClient client, boolean debug) { //todo: always set no follow redirects, rather should the user be allowed //to set this? this will effect the request creation/submisstion //document info about the cookie handler client = client.clone();/*ww w . ja v a 2 s . c o m*/ client.setFollowRedirects(false); if (client.getCookieHandler() == null) { client.setCookieHandler(new CookieManager()); } this.client = client; this.debug = debug; }
From source file:com.uber.sdk.rides.client.internal.RetrofitUberRidesClient.java
License:Open Source License
/** * Builds a RestAdapter./*from w w w . j a va2s . c o m*/ */ private static RestAdapter buildRestAdapter(final Session session, String endpointHost, final OAuth2Helper oAuth2Helper, RestAdapter.LogLevel logLevel, OkHttpClient httpClient) throws IOException { RequestInterceptor requestInterceptor = new RequestInterceptor() { @Override public void intercept(RequestFacade requestFacade) { Credential credential = session.getCredential(); if (credential != null) { oAuth2Helper.refreshCredentialIfNeeded(credential); requestFacade.addHeader("Authorization", "Bearer " + credential.getAccessToken()); } else { requestFacade.addHeader("Authorization", "Token " + session.getServerToken()); } if (session.getLocale() != null) { requestFacade.addHeader("Accept-Language", session.getLocale().getLanguage()); } requestFacade.addHeader("X-Uber-User-Agent", "Java Rides SDK v" + LIB_VERSION); } }; if (httpClient == null) { httpClient = new OkHttpClient(); httpClient.setConnectTimeout(1, TimeUnit.MINUTES); httpClient.setReadTimeout(1, TimeUnit.MINUTES); httpClient.setFollowRedirects(false); httpClient.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request oldRequest = chain.request(); Response response = chain.proceed(oldRequest); if (response.isRedirect()) { String redirectUrl = response.header(HttpHeaders.LOCATION); Request newRequest = oldRequest.newBuilder().url(redirectUrl).build(); return chain.proceed(newRequest); } return response; } }); } return new RestAdapter.Builder().setEndpoint(endpointHost) .setConverter(new GsonConverter(new GsonBuilder().create())) .setRequestInterceptor(requestInterceptor).setClient(new OkClient(httpClient)).setLogLevel(logLevel) .build(); }
From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java
License:Apache License
private HttpClientBuilder getHttpClient(HttpContext httpContext) { HttpClientBuilder client = HttpClients.custom(); client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager OkHttpClient c = new OkHttpClient(); c.setFollowRedirects(true); // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth client.setRedirectStrategy(new LaxRedirectStrategy()); c.setCookieHandler(cookieManager);//from ww w . ja v a 2s.co m c.setConnectTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); c.setReadTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); c.setWriteTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); CredentialsProvider credentialsProvider = getCredentialsProvider(); client.setDefaultCredentialsProvider(credentialsProvider); if (authData.isLoginAndPasswordAvailable()) { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword())); BasicScheme basicAuth = new BasicScheme(); httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth); client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData)); } client.addInterceptorLast(new UserAgentHttpRequestInterceptor()); for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) { client = httpClientBuilderExtension.extend(client, authData); credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider, authData); } return client; }
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);//w w w . j ava 2 s. co m 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 w w w .ja va 2 s .c o 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:io.apiman.gateway.platforms.servlet.connectors.HttpConnectorFactory.java
License:Apache License
/** * @return a new http client/*w w w . jav a2 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 ww . ja v a 2 s . 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 . j a v a2 s . c om 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.apache.nifi.processors.standard.InvokeHTTP.java
License:Apache License
@OnScheduled public void setUpClient(final ProcessContext context) throws IOException { okHttpClientAtomicReference.set(null); OkHttpClient okHttpClient = new OkHttpClient(); // Add a proxy if set final String proxyHost = context.getProperty(PROP_PROXY_HOST).getValue(); final Integer proxyPort = context.getProperty(PROP_PROXY_PORT).asInteger(); if (proxyHost != null && proxyPort != null) { final Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); okHttpClient.setProxy(proxy);/*from w w w .ja v a 2s . c o m*/ } // Set timeouts okHttpClient.setConnectTimeout( (context.getProperty(PROP_CONNECT_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()), TimeUnit.MILLISECONDS); okHttpClient.setReadTimeout( context.getProperty(PROP_READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue(), TimeUnit.MILLISECONDS); // Set whether to follow redirects okHttpClient.setFollowRedirects(context.getProperty(PROP_FOLLOW_REDIRECTS).asBoolean()); final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE) .asControllerService(SSLContextService.class); final SSLContext sslContext = sslService == null ? null : sslService.createSSLContext(ClientAuth.NONE); // check if the ssl context is set and add the factory if so if (sslContext != null) { okHttpClient.setSslSocketFactory(sslContext.getSocketFactory()); } // check the trusted hostname property and override the HostnameVerifier String trustedHostname = trimToEmpty(context.getProperty(PROP_TRUSTED_HOSTNAME).getValue()); if (!trustedHostname.isEmpty()) { okHttpClient.setHostnameVerifier( new OverrideHostnameVerifier(trustedHostname, okHttpClient.getHostnameVerifier())); } setAuthenticator(okHttpClient, context); useChunked = context.getProperty(PROP_USE_CHUNKED_ENCODING).asBoolean(); okHttpClientAtomicReference.set(okHttpClient); }
From source file:org.mythtv.services.api.v027.VideoServiceTest.java
License:Apache License
public void setUp() throws Exception { OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setFollowRedirects(true); context = (MythTvApi027Context) MythTvApiContext.newBuilder().setOkHttpClient(okHttpClient) .setHostName("master").setVersion(ApiVersion.v027).build(); videoService = context.getVideoService(); }