private HttpClient getClient() { if (client == null) { HttpClientBuilder clientBuilder = HttpClients.custom(); RequestConfig.Builder configBuilder = RequestConfig.custom(); if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) { isUsingProxy = true; InetSocketAddress adr = (InetSocketAddress) proxy.address(); clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort())); } if (timeout != null) { configBuilder.setConnectTimeout(timeout.intValue()); } if (readTimeout != null) { configBuilder.setSocketTimeout(readTimeout.intValue()); } if (followRedirects != null) { configBuilder.setRedirectsEnabled(followRedirects.booleanValue()); } if (hostnameverifier != null) { SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(getSSLContext(), hostnameverifier); clientBuilder.setSSLSocketFactory(sslConnectionFactory); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnectionFactory) .register("http", PlainConnectionSocketFactory.INSTANCE) .build(); clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry)); } clientBuilder.setDefaultRequestConfig(configBuilder.build()); client = clientBuilder.build(); } return client; }
/** * Prior to {@code Build()}, host, port, and endpoint must be specified. * * @return a {@link JobClient}. * @throws URISyntaxException */ public JobClient build() throws URISyntaxException { // The definition of the following parameters are optional. if (_statusUpdateIntervalSeconds == null) { _statusUpdateIntervalSeconds = DEFAULT_STATUS_UPDATE_INTERVAL_SECONDS; } if (_batchRequestSize == null) { _batchRequestSize = DEFAULT_BATCH_REQUEST_SIZE; } if (_requestTimeoutSeconds == null) { _requestTimeoutSeconds = DEFAULT_REQUEST_TIMEOUT_SECONDS; } RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(_requestTimeoutSeconds * 1000) .setConnectTimeout(_requestTimeoutSeconds * 1000) .setConnectionRequestTimeout(_requestTimeoutSeconds * 1000) .setStaleConnectionCheckEnabled(true) .build(); _httpClientBuilder.setDefaultRequestConfig(requestConfig); _httpClientBuilder.setRetryHandler(new StandardHttpRequestRetryHandler()); return new JobClient( Preconditions.checkNotNull(_host, "host must be set"), Preconditions.checkNotNull(_port, "port must be set"), Preconditions.checkNotNull(_endpoint, "endpoint must be set"), _statusUpdateIntervalSeconds, _batchRequestSize, _instanceDecorator, _httpClientBuilder.build()); }
/** Executes the request against the appliance API (Should not be called directly). */ @Override public MuteCheckResponse executeRequest() throws MorpheusApiRequestException { CloseableHttpClient client = null; try { URIBuilder uriBuilder = new URIBuilder(endpointUrl); uriBuilder.setPath("/api/monitoring/checks/" + this.getCheckId() + "/quarantine"); HttpPut request = new HttpPut(uriBuilder.build()); this.applyHeaders(request); HttpClientBuilder clientBuilder = HttpClients.custom(); clientBuilder.setDefaultRequestConfig(this.getRequestConfig()); client = clientBuilder.build(); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(generateRequestBody())); CloseableHttpResponse response = client.execute(request); return MuteCheckResponse.createFromStream(response.getEntity().getContent()); } catch (Exception ex) { // Throw custom exception throw new MorpheusApiRequestException( "Error Performing API Request for muting/unmuting a Check", ex); } finally { if (client != null) { try { client.close(); } catch (IOException io) { // ignore } } } }
private static CloseableHttpClient createHTTPClient( PrivateKey privateKey, X509Certificate certificate, boolean validateCertificate) { // HttpClientBuilder clientBuilder = HttpClientBuilder.create(); HttpClientBuilder clientBuilder = HttpClients.custom(); try { SSLContext sslContext = TrustUtils.getCustomSSLContext(privateKey, certificate, validateCertificate); clientBuilder.setSslcontext(sslContext); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | KeyManagementException | UnrecoverableKeyException | NoSuchProviderException ex) { LOGGER.log(Level.WARNING, "unable to set SSL context", ex); return null; } RequestConfig.Builder rcBuilder = RequestConfig.custom(); // handle redirects :) rcBuilder.setRedirectsEnabled(true); // HttpClient bug caused by Lighttpd rcBuilder.setExpectContinueEnabled(false); clientBuilder.setDefaultRequestConfig(rcBuilder.build()); // create connection manager // ClientConnectionManager connMgr = new SingleClientConnManager(params, registry); // return new DefaultHttpClient(connMgr, params); return clientBuilder.build(); }
private static HttpClient createHttpClient() { RequestConfig config = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build(); HttpClientBuilder hcBuilder = HttpClients.custom(); hcBuilder.setDefaultRequestConfig(config); return hcBuilder.build(); }
public void init() { if (httpClient == null) { RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(bookmakerConfig.getTimeout()); requestBuilder = requestBuilder.setConnectionRequestTimeout(bookmakerConfig.getTimeout()); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setDefaultRequestConfig(requestBuilder.build()); httpClient = builder.build(); } }
/** * Sets the timeouts of the HTTP client. * * @param connectionTimeout timeout until connection established in milliseconds. Zero means no * timeout. * @param socketTimeout timeout for waiting for data in milliseconds. Zero means no timeout. * @param maxRequests maximum number of connections to a particuar host */ public static void setParams(int connectionTimeout, int socketTimeout, int maxRequests) { PrudentHttpEntityResolver.maxRequests = maxRequests; PoolingHttpClientConnectionManager phcConnMgr; Registry<ConnectionSocketFactory> registry = // RegistryBuilder.<ConnectionSocketFactory>create() // .register("http", PlainConnectionSocketFactory.getSocketFactory()) // .register("https", SSLConnectionSocketFactory.getSocketFactory()) // .build(); HttpClientBuilder builder = HttpClients.custom(); builder.setRedirectStrategy(new LaxRedirectStrategy()); builder.setMaxConnPerRoute(maxRequests); builder.setMaxConnTotal(200); if ("true".equals(System.getProperty("nu.validator.xml.promiscuous-ssl", "false"))) { // try { SSLContext promiscuousSSLContext = new SSLContextBuilder() // .loadTrustMaterial( null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }) .build(); builder.setSslcontext(promiscuousSSLContext); HostnameVerifier verifier = // SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLConnectionSocketFactory promiscuousSSLConnSocketFactory = // new SSLConnectionSocketFactory(promiscuousSSLContext, verifier); registry = RegistryBuilder.<ConnectionSocketFactory>create() // .register("https", promiscuousSSLConnSocketFactory) // .register("http", PlainConnectionSocketFactory.getSocketFactory()) // .build(); } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException | NumberFormatException e) { e.printStackTrace(); } } phcConnMgr = new PoolingHttpClientConnectionManager(registry); phcConnMgr.setDefaultMaxPerRoute(maxRequests); phcConnMgr.setMaxTotal(200); builder.setConnectionManager(phcConnMgr); RequestConfig.Builder config = RequestConfig.custom(); config.setCircularRedirectsAllowed(true); config.setMaxRedirects(20); // Gecko default config.setConnectTimeout(connectionTimeout); config.setCookieSpec(CookieSpecs.BEST_MATCH); config.setSocketTimeout(socketTimeout); client = builder.setDefaultRequestConfig(config.build()).build(); }
static { HttpClientBuilder custom = HttpClients.custom(); custom.setUserAgent("Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0"); RequestConfig config = RequestConfig.custom() .setConnectionRequestTimeout(5 * 1000) .setSocketTimeout(30 * 1000) .setConnectTimeout(5 * 1000) .build(); custom.setDefaultRequestConfig(config); httpclient = custom.build(); minHttpclient = HttpClients.createMinimal(); }
private ActivityClient(String host, int port, int socketTimeout) { RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(socketTimeout); requestBuilder = requestBuilder.setConnectionRequestTimeout(socketTimeout); requestBuilder = requestBuilder.setSocketTimeout(socketTimeout); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setDefaultRequestConfig(requestBuilder.build()); httpClient = builder.build(); this.connectionUrl = "http://" + host + ":" + port + "/connection"; this.queryUrl = "http://" + host + ":" + port + "/query"; this.preparedStatementExecutionUrl = "http://" + host + ":" + port + "/prepared-statement-execution"; this.batchUrl = "http://" + host + ":" + port + "/batch-execution"; this.preparedStatementPreparationUrl = "http://" + host + ":" + port + "/prepared-statement-preparation"; }
/** * Configures a {@link HttpClientBuilder} to call the informed {@link BearerCredentialsSupport} * object to answer "bearer" challenges, such as <code>401 Unauthorized</code> responses. The * {@link BearerCredentialsSupport} object can return a token an hide <code>401</code> results * from users. */ public static void configureClientBuilder( HttpClientBuilder httpBuilder, BearerCredentialsSupport support) { // Configure to use "bearer" as preferred authentication scheme (without // this, the client uses basic, diggest, etc). Builder configBuilder = RequestConfig.custom() .setTargetPreferredAuthSchemes(Arrays.asList(new String[] {BearerAuthentication.NAME})); httpBuilder.setDefaultRequestConfig(configBuilder.build()); // Provide a custom "bearer" authentication provider. RegistryBuilder<AuthSchemeProvider> schemeProviderBuilder = RegistryBuilder.create(); schemeProviderBuilder.register( BearerAuthentication.NAME, BearerAuthenticationProvider.INSTANCE); httpBuilder.setDefaultAuthSchemeRegistry(schemeProviderBuilder.build()); // Configure to use the CloudCredentialsProvider. httpBuilder.setDefaultCredentialsProvider(new BearerCredentialsProvider(support)); }
public FusionPipelineClient( String endpointUrl, String fusionUser, String fusionPass, String fusionRealm) throws MalformedURLException { globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build(); cookieStore = new BasicCookieStore(); this.fusionUser = fusionUser; this.fusionPass = fusionPass; this.fusionRealm = fusionRealm; // build the HttpClient to be used for all requests HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore); if (fusionUser != null && fusionRealm == null) httpClientBuilder.addInterceptorFirst( new PreEmptiveBasicAuthenticator(fusionUser, fusionPass)); httpClient = httpClientBuilder.build(); HttpClientUtil.setMaxConnections(httpClient, 500); HttpClientUtil.setMaxConnectionsPerHost(httpClient, 100); originalEndpoints = Arrays.asList(endpointUrl.split(",")); try { sessions = establishSessions(originalEndpoints, fusionUser, fusionPass, fusionRealm); } catch (Exception exc) { if (exc instanceof RuntimeException) { throw (RuntimeException) exc; } else { throw new RuntimeException(exc); } } random = new Random(); jsonObjectMapper = new ObjectMapper(); requestCounter = new AtomicInteger(0); }
protected synchronized HttpClient getHttpClient(final String url) throws DSSException { if (httpClient != null) { return httpClient; } else { HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder = configCredentials(httpClientBuilder, url); final RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(timeoutSocket) .setConnectionRequestTimeout(timeoutConnection) .build(); httpClientBuilder = httpClientBuilder.setDefaultRequestConfig(requestConfig); httpClientBuilder.setConnectionManager(getConnectionManager()); httpClient = httpClientBuilder.build(); return httpClient; } }
@Override @Guarded(by = STARTED) public HttpClientBuilder prepare(final @Nullable Customizer customizer) { final HttpClientPlan plan = new HttpClientPlan(); // attach connection manager early, so customizer has chance to replace it if needed plan.getClient().setConnectionManager(sharedConnectionManager); // apply defaults defaultsCustomizer.customize(plan); // apply globals new ConfigurationCustomizer(getConfigurationInternal()).customize(plan); // apply instance customization if (customizer != null) { customizer.customize(plan); } // apply plan to builder HttpClientBuilder builder = plan.getClient(); builder.setDefaultConnectionConfig(plan.getConnection().build()); builder.setDefaultSocketConfig(plan.getSocket().build()); builder.setDefaultRequestConfig(plan.getRequest().build()); builder.setDefaultCredentialsProvider(plan.getCredentials()); builder.addInterceptorFirst( (HttpRequest request, HttpContext context) -> { // add custom http-context attributes for (Entry<String, Object> entry : plan.getAttributes().entrySet()) { // only set context attribute if not already set, to allow per request overrides if (context.getAttribute(entry.getKey()) == null) { context.setAttribute(entry.getKey(), entry.getValue()); } } // add custom http-request headers for (Entry<String, String> entry : plan.getHeaders().entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } }); builder.addInterceptorLast( (HttpRequest httpRequest, HttpContext httpContext) -> { if (outboundLog.isDebugEnabled()) { httpContext.setAttribute(CTX_REQ_STOPWATCH, Stopwatch.createStarted()); httpContext.setAttribute(CTX_REQ_URI, getRequestURI(httpContext)); outboundLog.debug( "{} > {}", httpContext.getAttribute(CTX_REQ_URI), httpRequest.getRequestLine()); } }); builder.addInterceptorLast( (HttpResponse httpResponse, HttpContext httpContext) -> { Stopwatch stopwatch = (Stopwatch) httpContext.getAttribute(CTX_REQ_STOPWATCH); if (stopwatch != null) { outboundLog.debug( "{} < {} @ {}", httpContext.getAttribute(CTX_REQ_URI), httpResponse.getStatusLine(), stopwatch); } }); return builder; }