Java Code Examples for okhttp3.OkHttpClient.Builder#build()

The following examples show how to use okhttp3.OkHttpClient.Builder#build() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OKHttpFactory.java    From flower with Apache License 2.0 6 votes vote down vote up
private void initOKHttp() {
  Builder builder = new OkHttpClient().newBuilder();
  builder.connectTimeout(httpConfig.getConnectTimeout(), TimeUnit.MILLISECONDS);
  builder.writeTimeout(httpConfig.getWriteTimeout(), TimeUnit.MILLISECONDS);
  builder.readTimeout(httpConfig.getReadTimeout(), TimeUnit.MILLISECONDS);

  ExecutorService executorService = new ThreadPoolExecutor(8, Runtime.getRuntime().availableProcessors() * 8, 60,
      TimeUnit.SECONDS, new SynchronousQueue<>(), new NamedThreadFactory("flower-http"));

  Dispatcher dispatcher = new Dispatcher(executorService);
  dispatcher.setMaxRequests(256);
  dispatcher.setMaxRequestsPerHost(Math.max(32, Runtime.getRuntime().availableProcessors() * 8));

  builder.dispatcher(dispatcher);
  builder.retryOnConnectionFailure(true);
  builder.connectionPool(new ConnectionPool());

  this.template = builder.build();
}
 
Example 2
Source File: ChannelManagementClientBuilder.java    From line-bot-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Build a new {@link ChannelManagementSyncClient}.
 */
public ChannelManagementSyncClient build() {
    final Builder okHttpClientBuilder = new Builder();

    okHttpClientBuilder
            .addInterceptor(buildAuthenticationInterceptor(channelTokenSupplier))
            .addInterceptor(buildLoggingInterceptor());

    final OkHttpClient okHttpClient = okHttpClientBuilder.build();

    final Retrofit.Builder retrofitBuilder = createDefaultRetrofitBuilder();

    retrofitBuilder.client(okHttpClient);
    retrofitBuilder.baseUrl(apiEndPoint.toString());
    final Retrofit retrofit = retrofitBuilder.build();

    final ChannelManagementClientRetrofitIface retrofitIface =
            retrofit.create(ChannelManagementClientRetrofitIface.class);
    return ChannelManagementSyncClientImpl.of(retrofitIface);
}
 
Example 3
Source File: NetworkModule.java    From Popular-Movies-App with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
OkHttpClient providesOkHttpClient(Cache cache) {
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    Builder builder = new Builder()
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(TIMEOUT, TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            .addInterceptor(new AuthorizationInterceptor())
            .cache(cache);

    return builder.build();
}
 
Example 4
Source File: OkHttpAdapter.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
private void initImpl() {
	synchronized (this) {
		if (impl == null) {
			Builder builder = new OkHttpClient.Builder();

			if (networkTimeout != null) {
				builder.readTimeout(networkTimeout, TimeUnit.MILLISECONDS);
			}

			for (OkHttpAdapterListener listener : listeners) {
				listener.onBuild(builder);
			}
			impl = builder.build();
		}
	}
}
 
Example 5
Source File: EntityApi.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
EntityClient(ISession session, boolean activeCaching) {
	super();

	ExecutorService executor = RateLimitExecutor.create(30, BitbucketSession.class, session.id());
	BitbucketInterceptor interceptors = new BitbucketInterceptor(session);
	String baseurl = BitbucketPropertiesUtil.get(API_BASE_URL);

	if (!baseurl.endsWith("/")) baseurl += "/"; // FIXME Validate in Model with EVL 

	Builder clientBuilder = AbstractClient.okHttp(executor);
	
	ICache localcache = new BitbucketCacheManager().getCacheInstance();
	if (activeCaching && localcache != null && !localcache.isDistributed()) {
		clientBuilder = clientBuilder.cache(localcache.initializeLocal());
		LOG.info("enabling local okhttp cache");
	}
				
	clientBuilder = clientBuilder.addNetworkInterceptor(CacheControlInterceptor.REWRITE_CACHE_CONTROL_INTERCEPTOR);
	clientBuilder = clientBuilder.addInterceptor(interceptors.mainInterceptor(activeCaching));
				
	this.client = clientBuilder.build();

	this.callbackEndpoint = AbstractClient.retrofit(client, baseurl).create(IEntityEndpoint.class);
	this.paginationPolicy = BitbucketPagination.get();
}
 
Example 6
Source File: SearchApi.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
SearchClient(ISession session, boolean activeCaching) {
	super();

	ExecutorService executor = RateLimitExecutor.create(30, BitbucketSession.class, session.id());
	BitbucketInterceptor interceptors = new BitbucketInterceptor(session);
	String baseurl = BitbucketPropertiesUtil.get(API_BASE_URL);

	if (!baseurl.endsWith("/")) baseurl += "/"; // FIXME Validate in Model with EVL 

	Builder clientBuilder = AbstractClient.okHttp(executor);
	
	ICache localcache = new BitbucketCacheManager().getCacheInstance();
	if (activeCaching && localcache != null && !localcache.isDistributed()) {
		clientBuilder = clientBuilder.cache(localcache.initializeLocal());
		LOG.info("enabling local okhttp cache");
	}
				
	clientBuilder = clientBuilder.addNetworkInterceptor(CacheControlInterceptor.REWRITE_CACHE_CONTROL_INTERCEPTOR);
	clientBuilder = clientBuilder.addInterceptor(interceptors.mainInterceptor(activeCaching));
				
	this.client = clientBuilder.build();

	this.callbackEndpoint = AbstractClient.retrofit(client, baseurl).create(ISearchEndpoint.class);
	this.paginationPolicy = BitbucketPagination.get();
}
 
Example 7
Source File: EntityApi.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
EntityClient(ISession session, boolean activeCaching) {
	super();

	ExecutorService executor = RateLimitExecutor.create(30, StackExchangeSession.class, session.id());
	StackExchangeInterceptor interceptors = new StackExchangeInterceptor(session);
	String baseurl = StackExchangePropertiesUtil.get(API_BASE_URL);

	if (!baseurl.endsWith("/")) baseurl += "/"; // FIXME Validate in Model with EVL 

	Builder clientBuilder = AbstractClient.okHttp(executor);
	
	ICache localcache = new StackExchangeCacheManager().getCacheInstance();
	if (activeCaching && localcache != null && !localcache.isDistributed()) {
		clientBuilder = clientBuilder.cache(localcache.initializeLocal());
		LOG.info("enabling local okhttp cache");
	}
				
	clientBuilder = clientBuilder.addNetworkInterceptor(CacheControlInterceptor.REWRITE_CACHE_CONTROL_INTERCEPTOR);
	clientBuilder = clientBuilder.addInterceptor(interceptors.mainInterceptor(activeCaching));
				
	this.client = clientBuilder.build();

	this.callbackEndpoint = AbstractClient.retrofit(client, baseurl).create(IEntityEndpoint.class);
	this.paginationPolicy = StackExchangePagination.get();
}
 
Example 8
Source File: SearchApi.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
SearchClient(ISession session, boolean activeCaching) {
	super();

	ExecutorService executor = RateLimitExecutor.create(30, StackExchangeSession.class, session.id());
	StackExchangeInterceptor interceptors = new StackExchangeInterceptor(session);
	String baseurl = StackExchangePropertiesUtil.get(API_BASE_URL);

	if (!baseurl.endsWith("/")) baseurl += "/"; // FIXME Validate in Model with EVL 

	Builder clientBuilder = AbstractClient.okHttp(executor);
	
	ICache localcache = new StackExchangeCacheManager().getCacheInstance();
	if (activeCaching && localcache != null && !localcache.isDistributed()) {
		clientBuilder = clientBuilder.cache(localcache.initializeLocal());
		LOG.info("enabling local okhttp cache");
	}
				
	clientBuilder = clientBuilder.addNetworkInterceptor(CacheControlInterceptor.REWRITE_CACHE_CONTROL_INTERCEPTOR);
	clientBuilder = clientBuilder.addInterceptor(interceptors.mainInterceptor(activeCaching));
				
	this.client = clientBuilder.build();

	this.callbackEndpoint = AbstractClient.retrofit(client, baseurl).create(ISearchEndpoint.class);
	this.paginationPolicy = StackExchangePagination.get();
}
 
Example 9
Source File: EntityApi.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
EntityClient(ISession session, boolean activeCaching) {
	super();

	ExecutorService executor = RateLimitExecutor.create(30, GitlabSession.class, session.id());
	GitlabInterceptor interceptors = new GitlabInterceptor(session);
	String baseurl = GitlabPropertiesUtil.get(API_BASE_URL);

	if (!baseurl.endsWith("/")) baseurl += "/"; // FIXME Validate in Model with EVL 

	Builder clientBuilder = AbstractClient.okHttp(executor);
	
	ICache localcache = new GitlabCacheManager().getCacheInstance();
	if (activeCaching && localcache != null && !localcache.isDistributed()) {
		clientBuilder = clientBuilder.cache(localcache.initializeLocal());
		LOG.info("enabling local okhttp cache");
	}
				
	clientBuilder = clientBuilder.addNetworkInterceptor(CacheControlInterceptor.REWRITE_CACHE_CONTROL_INTERCEPTOR);
	clientBuilder = clientBuilder.addInterceptor(interceptors.mainInterceptor(activeCaching));
				
	this.client = clientBuilder.build();

	this.callbackEndpoint = AbstractClient.retrofit(client, baseurl).create(IEntityEndpoint.class);
	this.paginationPolicy = GitlabPagination.get();
}
 
Example 10
Source File: SearchApi.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
SearchClient(ISession session, boolean activeCaching) {
	super();

	ExecutorService executor = RateLimitExecutor.create(30, GitlabSession.class, session.id());
	GitlabInterceptor interceptors = new GitlabInterceptor(session);
	String baseurl = GitlabPropertiesUtil.get(API_BASE_URL);

	if (!baseurl.endsWith("/")) baseurl += "/"; // FIXME Validate in Model with EVL 

	Builder clientBuilder = AbstractClient.okHttp(executor);
	
	ICache localcache = new GitlabCacheManager().getCacheInstance();
	if (activeCaching && localcache != null && !localcache.isDistributed()) {
		clientBuilder = clientBuilder.cache(localcache.initializeLocal());
		LOG.info("enabling local okhttp cache");
	}
				
	clientBuilder = clientBuilder.addNetworkInterceptor(CacheControlInterceptor.REWRITE_CACHE_CONTROL_INTERCEPTOR);
	clientBuilder = clientBuilder.addInterceptor(interceptors.mainInterceptor(activeCaching));
				
	this.client = clientBuilder.build();

	this.callbackEndpoint = AbstractClient.retrofit(client, baseurl).create(ISearchEndpoint.class);
	this.paginationPolicy = GitlabPagination.get();
}
 
Example 11
Source File: SearchApi.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
SearchClient(ISession session, boolean activeCaching) {
	super();

	ExecutorService executor = RateLimitExecutor.create(30, GitHubSession.class, session.id());
	GitHubInterceptor interceptors = new GitHubInterceptor(session);
	String baseurl = GitHubPropertiesUtil.get(API_BASE_URL);

	if (!baseurl.endsWith("/"))
		baseurl += "/"; // FIXME Validate in Model with EVL

	Builder clientBuilder = AbstractClient.okHttp(executor);

	ICache localcache = new GitHubCacheManager().getCacheInstance();
	if (activeCaching && localcache != null && !localcache.isDistributed()) {
		clientBuilder = clientBuilder.cache(localcache.initializeLocal());
		LOG.info("enabling local okhttp cache");
	}

	// FIXME update generator
	clientBuilder = clientBuilder
			.addNetworkInterceptor(CacheControlInterceptor.REWRITE_CACHE_CONTROL_INTERCEPTOR);
	clientBuilder = clientBuilder.addInterceptor(interceptors.mainInterceptor(activeCaching));

	this.client = clientBuilder.build();

	this.callbackEndpoint = AbstractClient.retrofit(client, baseurl).create(ISearchEndpoint.class);
	this.paginationPolicy = GitHubSearchAPIPagination.get();
}
 
Example 12
Source File: HttpClient.java    From StubbornJava with MIT License 5 votes vote down vote up
public static OkHttpClient trustAllSslClient(OkHttpClient client) {
    log.warn("Using the trustAllSslClient is highly discouraged and should not be used in Production!");
    Builder builder = client.newBuilder();
    builder.sslSocketFactory(trustAllSslSocketFactory, (X509TrustManager)trustAllCerts[0]);
    builder.hostnameVerifier(new HostnameVerifier() {
      @Override
      public boolean verify(String hostname, SSLSession session) {
        return true;
      }
    });
    return builder.build();
}
 
Example 13
Source File: OkHttpAdapter.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private synchronized void initImpl() {
    if (impl == null) {
        Builder builder = new OkHttpClient.Builder();

        if (networkTimeout != null) {
            builder.readTimeout(networkTimeout, TimeUnit.MILLISECONDS);
        }

        for (OkHttpAdapterListener listener : nativeListeners) {
            listener.onBuild(builder);
        }
        impl = builder.build();
    }
}
 
Example 14
Source File: HttpClient.java    From StubbornJava with MIT License 5 votes vote down vote up
public static OkHttpClient trustAllSslClient(OkHttpClient client) {
    log.warn("Using the trustAllSslClient is highly discouraged and should not be used in Production!");
    Builder builder = client.newBuilder();
    builder.sslSocketFactory(trustAllSslSocketFactory, (X509TrustManager)trustAllCerts[0]);
    builder.hostnameVerifier(new HostnameVerifier() {
      @Override
      public boolean verify(String hostname, SSLSession session) {
        return true;
      }
    });
    return builder.build();
}
 
Example 15
Source File: HttpConnection.java    From PocketMaps with MIT License 5 votes vote down vote up
private static OkHttpClient getOkHttpClient() {
    if (client == null) {
        Builder b = new Builder();
        b.connectTimeout(TIMEOUT_CONNECTION, TimeUnit.MILLISECONDS);
        b.readTimeout(TIMEOUT_SOCKET, TimeUnit.MILLISECONDS);
        client = b.build();
        /*
        client.setConnectTimeout(TIMEOUT_CONNECTION, TimeUnit.MILLISECONDS);
        client.setReadTimeout(TIMEOUT_SOCKET, TimeUnit.MILLISECONDS);
        */
    }
    return client;
}
 
Example 16
Source File: QueryStatusServlet.java    From yanagishima with Apache License 2.0 5 votes vote down vote up
private OkHttpClient buildClient(HttpServletRequest request) {
	String user = request.getParameter("user");
	String password = request.getParameter("password");
	if (user != null && password != null) {
		Builder builder = httpClient.newBuilder();
		builder.addInterceptor(basicAuth(user, password));
		return builder.build();
	}
	return httpClient;
}
 
Example 17
Source File: OkHttpFetcher.java    From ache with Apache License 2.0 4 votes vote down vote up
private OkHttpClient getCustomOkHttpClient() {
    
    final ConnectionSpec specModernTLS = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .cipherSuites(new CustomCipherSuites().getCustomCipherSuites().toArray(new CipherSuite[0]))
            .build();

    final ConnectionSpec specClearText = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT)
            .build();

    final ConnectionSpec specCompatibleTLS = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
            .build();

    final List<ConnectionSpec> specs = new ArrayList<>();
    specs.add(specModernTLS);
    specs.add(specClearText);
    specs.add(specCompatibleTLS);

    X509TrustManager trustManager;
    SSLSocketFactory sslSocketFactory;

    try {
        trustManager = defaultTrustManager();
        sslSocketFactory = defaultSslSocketFactory(trustManager);

        SSLSocketFactory customSslSocketFactory =
                new DelegatingSSLSocketFactory(sslSocketFactory) {
                    @Override
                    protected SSLSocket configureSocket(SSLSocket socket) throws IOException {
                        socket.setEnabledCipherSuites(javaNames(specModernTLS.cipherSuites()));
                        return socket;
                    }
                };

        Builder clientBuilder = new OkHttpClient.Builder().connectionSpecs(specs)
                .sslSocketFactory(customSslSocketFactory, trustManager)
                .connectTimeout(connectTimeoutTime, TimeUnit.MILLISECONDS)
                .readTimeout(readTimeoutTime, TimeUnit.MILLISECONDS);

        if (cookieJar != null) {
            clientBuilder.cookieJar(cookieJar);
        }

        return clientBuilder.build();

    } catch (GeneralSecurityException gse) {
    }

    return new OkHttpClient();
}
 
Example 18
Source File: ClientHttpRequestFactoryFactory.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
static ClientHttpRequestFactory usingOkHttp3(ClientOptions options, SslConfiguration sslConfiguration)
		throws GeneralSecurityException, IOException {

	Builder builder = new Builder();

	if (hasSslConfiguration(sslConfiguration)) {

		TrustManager[] trustManagers = getTrustManagers(sslConfiguration);

		if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
			throw new IllegalStateException(
					"Unexpected default trust managers:" + Arrays.toString(trustManagers));
		}

		X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
		SSLContext sslContext = getSSLContext(sslConfiguration, trustManagers);

		builder.sslSocketFactory(sslContext.getSocketFactory(), trustManager);
	}

	builder.connectTimeout(options.getConnectionTimeout().toMillis(), TimeUnit.MILLISECONDS)
			.readTimeout(options.getReadTimeout().toMillis(), TimeUnit.MILLISECONDS);

	return new OkHttp3ClientHttpRequestFactory(builder.build());
}
 
Example 19
Source File: CurlThread.java    From fiery with Apache License 2.0 4 votes vote down vote up
private String postHttp(String url, String postData) {
    String result = "";

    Builder builder = new Builder();
    builder.connectTimeout(10000, TimeUnit.MILLISECONDS);
    builder.readTimeout(10000, TimeUnit.MILLISECONDS);
    builder.writeTimeout(10000, TimeUnit.MILLISECONDS);
    builder.followRedirects(true);
    builder.retryOnConnectionFailure(false);
    OkHttpClient client = builder.build();

    //MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
    RequestBody body = new FormBody.Builder().add("contents", postData).build();
    //RequestBody.create(mediaType, "contents=" + postData);

    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    try {
        Response response = client.newCall(request).execute();
        result = response.body().string();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;

    /*
    String result = "";

    if (postData.trim().length() == 0) {
        return "";
    }
    HttpPost httppost = new HttpPost(url);
    CloseableHttpClient httpClient = HttpClients.createDefault();

    //header
    httppost.addHeader("connection", "close");
    httppost.addHeader("user-agent", "Ragnar Fiery LogPusher");
    httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");

    //Configure
    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(10000)
            .setConnectTimeout(10000)
            .setConnectionRequestTimeout(20000)
            .setContentCompressionEnabled(true)
            .setExpectContinueEnabled(true)
            .setMaxRedirects(3)
            .setRedirectsEnabled(true)
            .build();
    httppost.setConfig(requestConfig);

    //set parameter
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("contents", postData));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
    httppost.setEntity(entity);

    try {
        CloseableHttpResponse response = httpClient.execute(httppost);
        result = EntityUtils.toString(response.getEntity());

    } catch (Exception e) {
        e.printStackTrace();
        log.error("http post error:" + e.getMessage());
    }

    httppost.releaseConnection();
    return result;
    */
}
 
Example 20
Source File: UnixDomainSocketITCase.java    From flink-statefun with Apache License 2.0 4 votes vote down vote up
/** returns an {@link OkHttpClient} that connects trough the provided socket file. */
private static OkHttpClient udsSocketClient(File sockFile) {
  Builder sharedClient = OkHttpUtils.newClient().newBuilder();
  OkHttpUnixSocketBridge.configureUnixDomainSocket(sharedClient, sockFile);
  return sharedClient.build();
}