Build an HttpClient

@param customiser

@return
979817
public CloseableHttpClient createHttpClient(final Consumer<HttpClientBuilder> customiser)
	{
		final HttpClientBuilder builder = HttpClientBuilder.create();

		// By default set long call timeouts
		{
			RequestConfig.Builder requestBuilder = RequestConfig.custom();

			requestBuilder.setConnectTimeout((int) connectionTimeout.getMilliseconds())
			              .setSocketTimeout((int) socketTimeout.getMilliseconds());

			builder.setDefaultRequestConfig(requestBuilder.build());
		}

		// Set the default keepalive setting
		if (noKeepalive)
			builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());

		// By default share the common connection provider
		builder.setConnectionManager(connectionManager);

		// By default use the JRE default route planner for proxies
		builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));

		// Allow customisation
		if (customiser != null)
			customiser.accept(builder);

		return builder.build();
	}
96322
public HttpRequestFactory makeClient(DatastoreOptions options) {
    Credential credential = options.getCredential();
    HttpTransport transport = options.getTransport();
    if (transport == null) {
      transport = credential == null ? new NetHttpTransport() : credential.getTransport();
      transport = transport == null ? new NetHttpTransport() : transport;
    }
    return transport.createRequestFactory(credential);
  }
817151
function HttpClient(connectionConfig)
{
  // save the connection config
  this._connectionConfig = connectionConfig;

  // check that we have a valid request module
  var requestModule = this.getRequestModule();
  Errors.assertInternal(
      Util.isObject(requestModule) || Util.isFunction(requestModule));
}
206040
@Override
	public WebsocketSender uri(String uri) {
		return new WebsocketFinalizer(cachedConfiguration.bootstrap(b -> HttpClientConfiguration.uri(b, uri)));
	}
459792
def _create_http_client():
    """"""
    global _http_client

    defaults = {'user_agent': USER_AGENT}
    auth_username, auth_password = _credentials
    if auth_username and auth_password:
        defaults['auth_username'] = auth_username
        defaults['auth_password'] = auth_password

    _http_client = httpclient.AsyncHTTPClient(
        force_instance=True, defaults=defaults,
        max_clients=_max_clients)
1124832
private HttpAsyncClient buildHttpAsyncClient() throws IOReactorException {
        // Create I/O reactor configuration
        IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
                .setConnectTimeout(connectTimeout)
                .setSoTimeout(socketTimeout)
                .build();

        // Create a custom I/O reactor
        ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);

        // Create a connection manager with simple configuration.
        PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor);

        // Configure total max or per route limits for persistent connections
        // that can be kept in the pool or leased by the connection manager.
        connManager.setMaxTotal(maxTotal);
        connManager.setDefaultMaxPerRoute(defaultMaxPerRoute);

        return httpAsyncClient = HttpAsyncClients.custom()
                .useSystemProperties()
                .setConnectionManager(connManager)
                .build();
    }
1312314
public ServerBuilder annotatedService(String pathPrefix, Object service,
                                          Function<Service<HttpRequest, HttpResponse>,
                                                  ? extends Service<HttpRequest, HttpResponse>> decorator,
                                          Iterable<?> exceptionHandlersAndConverters) {
        requireNonNull(pathPrefix, "pathPrefix");
        requireNonNull(service, "service");
        requireNonNull(decorator, "decorator");
        requireNonNull(exceptionHandlersAndConverters, "exceptionHandlersAndConverters");

        defaultVirtualHostBuilderUpdated();
        defaultVirtualHostBuilder.annotatedService(pathPrefix, service, decorator,
                                                   exceptionHandlersAndConverters);
        return this;
    }
339836
@Singleton
    HttpClientHandler<HttpRequest<?>, HttpResponse<?>> httpClientHandler(HttpTracing httpTracing) {
        return HttpClientHandler.create(httpTracing, new HttpClientAdapter<HttpRequest<?>, HttpResponse<?>>() {
            @Override
            public String method(HttpRequest<?> request) {
                return request.getMethod().name();
            }

            @Override
            public String url(HttpRequest<?> request) {
                return request.getUri().toString();
            }

            @Override
            public String requestHeader(HttpRequest<?> request, String name) {
                return request.getHeaders().get(name);
            }

            @Override
            public Integer statusCode(HttpResponse<?> response) {
                return response.getStatus().getCode();
            }

            @Override
            public boolean parseServerIpAndPort(HttpRequest<?> request, Endpoint.Builder builder) {
                InetAddress address = request.getServerAddress().getAddress();
                return builder.parseIp(address);
            }

            @Override
            public String methodFromResponse(HttpResponse<?> httpResponse) {
                return httpResponse.getAttribute(HttpAttributes.METHOD_NAME, String.class)
                                   .orElseGet(() -> super.methodFromResponse(httpResponse));
            }

            @Override
            public String route(HttpResponse<?> response) {
                Optional<String> value = response.getAttribute(HttpAttributes.URI_TEMPLATE, String.class);
                return value.orElseGet(() -> super.route(response));
            }
        });
    }
587668
public static ClientHttpRequestFactory create(ClientOptions options) {

		Assert.notNull(options, "ClientOptions must not be null");

		try {
			if (HTTP_COMPONENTS_PRESENT) {
				logger.info("Using Apache HttpComponents HttpClient for HTTP connections");
				return HttpComponents.usingHttpComponents(options);
			}

			if (OKHTTP3_PRESENT) {
				logger.info("Using OkHttp3 for HTTP connections");
				return OkHttp3.usingOkHttp3(options);
			}

			if (NETTY_PRESENT) {
				logger.info("Using Netty for HTTP connections");
				return Netty.usingNetty(options);
			}
		} catch (GeneralSecurityException | IOException e) {
			logger.warn("Error configuring HTTP connections", e);
		}

		logger.info("Defaulting to java.net.HttpUrlConnection for HTTP connections");
		return HttpURLConnection.usingJdk(options);
	}
813730
public final HttpClient cookie(String name, Consumer<? super Cookie> cookieBuilder) {
		return new HttpClientCookie(this, name, cookieBuilder);
	}
825396
public HttpRequestInitializer getHttpRequestInitializer(
      final ServiceOptions<?, ?> serviceOptions) {
    Credentials scopedCredentials = serviceOptions.getScopedCredentials();
    final HttpRequestInitializer delegate =
        scopedCredentials != null && scopedCredentials != NoCredentials.getInstance()
            ? new HttpCredentialsAdapter(scopedCredentials)
            : null;
    HeaderProvider internalHeaderProvider =
        getInternalHeaderProviderBuilder(serviceOptions).build();
    final HeaderProvider headerProvider =
        serviceOptions.getMergedHeaderProvider(internalHeaderProvider);

    return new HttpRequestInitializer() {
      @Override
      public void initialize(HttpRequest httpRequest) throws IOException {
        if (delegate != null) {
          delegate.initialize(httpRequest);
        }
        if (connectTimeout >= 0) {
          httpRequest.setConnectTimeout(connectTimeout);
        }
        if (readTimeout >= 0) {
          httpRequest.setReadTimeout(readTimeout);
        }

        HttpHeadersUtils.setHeaders(httpRequest.getHeaders(), headerProvider.getHeaders());
      }
    };
  }
166853
def create(cls, custom_headers=None):
        

        if custom_headers is None:
            custom_headers = {}

        request_map = {

        }
        request_map_string = converter.class_to_json(request_map)
        request_map_string = cls._remove_field_for_request(request_map_string)

        api_client = client.ApiClient(cls._get_api_context())
        request_bytes = request_map_string.encode()
        endpoint_url = cls._ENDPOINT_URL_CREATE
        response_raw = api_client.post(endpoint_url, request_bytes,
                                       custom_headers)

        return BunqResponseSandboxUser.cast_from_bunq_response(
            cls._from_json(response_raw, cls._OBJECT_TYPE_POST)
        )
611034
public static ClientHttpConnector create(ClientOptions options) {
		HttpClient httpClient = HttpClient.create();

		if (usingCustomCerts(options)) {
			TrustManagerFactory trustManagerFactory =
					sslCertificateUtils.createTrustManagerFactory(options.getCaCertFiles());

			httpClient = httpClient.secure(sslContextSpec -> sslContextSpec
					.sslContext(SslContextBuilder.forClient()
							.sslProvider(SslProvider.JDK)
							.trustManager(trustManagerFactory)));
		} else {
			httpClient = httpClient.secure(sslContextSpec -> sslContextSpec
					.sslContext(SslContextBuilder.forClient()
							.sslProvider(SslProvider.JDK)));
		}

		if (options.getConnectionTimeout() != null) {
			httpClient = httpClient.tcpConfiguration(tcpClient ->
					tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
							Math.toIntExact(options.getConnectionTimeout().toMillis())));
		}

		return new ReactorClientHttpConnector(httpClient);
	}
836478
protected ConfiguredCloseableHttpClient createClient(
            final org.apache.http.impl.client.HttpClientBuilder builder,
            final InstrumentedHttpClientConnectionManager manager,
            final String name) {
        final String cookiePolicy = configuration.isCookiesEnabled() ? CookieSpecs.DEFAULT : CookieSpecs.IGNORE_COOKIES;
        final Integer timeout = (int) configuration.getTimeout().toMilliseconds();
        final Integer connectionTimeout = (int) configuration.getConnectionTimeout().toMilliseconds();
        final Integer connectionRequestTimeout = (int) configuration.getConnectionRequestTimeout().toMilliseconds();
        final long keepAlive = configuration.getKeepAlive().toMilliseconds();
        final ConnectionReuseStrategy reuseStrategy = keepAlive == 0
                ? new NoConnectionReuseStrategy()
                : new DefaultConnectionReuseStrategy();
        final HttpRequestRetryHandler retryHandler = configuration.getRetries() == 0
                ? NO_RETRIES
                : (httpRequestRetryHandler == null ? new DefaultHttpRequestRetryHandler(configuration.getRetries(),
                false) : httpRequestRetryHandler);

        final RequestConfig requestConfig
                = RequestConfig.custom().setCookieSpec(cookiePolicy)
                .setSocketTimeout(timeout)
                .setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .build();
        final SocketConfig socketConfig = SocketConfig.custom()
                .setTcpNoDelay(true)
                .setSoTimeout(timeout)
                .build();

        customizeBuilder(builder)
                .setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy, name))
                .setConnectionManager(manager)
                .setDefaultRequestConfig(requestConfig)
                .setDefaultSocketConfig(socketConfig)
                .setConnectionReuseStrategy(reuseStrategy)
                .setRetryHandler(retryHandler)
                .setUserAgent(createUserAgent(name));

        if (keepAlive != 0) {
            // either keep alive based on response header Keep-Alive,
            // or if the server can keep a persistent connection (-1), then override based on client's configuration
            builder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
                @Override
                public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                    final long duration = super.getKeepAliveDuration(response, context);
                    return (duration == -1) ? keepAlive : duration;
                }
            });
        }

        // create a tunnel through a proxy host if it's specified in the config
        final ProxyConfiguration proxy = configuration.getProxyConfiguration();
        if (proxy != null) {
            final HttpHost httpHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getScheme());
            builder.setRoutePlanner(new NonProxyListProxyRoutePlanner(httpHost, proxy.getNonProxyHosts()));
            // if the proxy host requires authentication then add the host credentials to the credentials provider
            final AuthConfiguration auth = proxy.getAuth();
            if (auth != null) {
                if (credentialsProvider == null) {
                    credentialsProvider = new BasicCredentialsProvider();
                }
                // set the AuthScope
                AuthScope authScope = new AuthScope(httpHost, auth.getRealm(), auth.getAuthScheme());

                // set the credentials type
                Credentials credentials = configureCredentials(auth);

                credentialsProvider.setCredentials(authScope, credentials);
            }
        }


        if (credentialsProvider != null) {
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }

        if (routePlanner != null) {
            builder.setRoutePlanner(routePlanner);
        }

        if (disableContentCompression) {
            builder.disableContentCompression();
        }

        if (redirectStrategy != null) {
            builder.setRedirectStrategy(redirectStrategy);
        }

        if (defaultHeaders != null) {
            builder.setDefaultHeaders(defaultHeaders);
        }

        if (verifier != null) {
            builder.setSSLHostnameVerifier(verifier);
        }

        if (httpProcessor != null) {
            builder.setHttpProcessor(httpProcessor);
        }

        if (serviceUnavailableRetryStrategy != null) {
            builder.setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy);
        }

        return new ConfiguredCloseableHttpClient(builder.build(), requestConfig);
    }
954859
public static HttpClient<ByteBuf, ByteBuf> newClient(ConnectionProviderFactory<ByteBuf, ByteBuf> providerFactory,
                                                         Observable<Host> hostStream) {
        return HttpClientImpl.create(providerFactory, hostStream);
    }
1280698
protected static HttpClient httpClient() throws Exception {
    return HttpClients.custom()
        .setHostnameVerifier(new AllowAllHostnameVerifier())
        .setSslcontext(SSLContexts.custom()
            .loadTrustMaterial(null, new TrustStrategy() {
              @Override
              public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
              }
            })
            .build())
        .build();
  }
559700
def _build_http_client(cls, session: AppSession):
        '''
        '''
        # TODO:
        # recorder = self._build_recorder()

        stream_factory = functools.partial(
            HTTPStream,
            ignore_length=session.args.ignore_length,
            keep_alive=session.args.http_keep_alive)

        return session.factory.new(
            'HTTPClient',
            connection_pool=session.factory['ConnectionPool'],
            stream_factory=stream_factory
         )