List of usage examples for org.apache.http.impl.client HttpClientBuilder setDefaultRequestConfig
public final HttpClientBuilder setDefaultRequestConfig(final RequestConfig config)
From source file:org.eclipse.jgit.transport.http.apache.HttpClientConnection.java
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;// w w w . j a v a 2 s. co m 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; }
From source file:com.xebialabs.overthere.winrm.WinRmClient.java
private void configureHttpClient(final HttpClientBuilder httpclient) throws GeneralSecurityException { configureTrust(httpclient);/*from w w w .ja v a 2 s . c o m*/ BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); httpclient.setDefaultCredentialsProvider(credentialsProvider); configureAuthentication(credentialsProvider, BASIC, new BasicUserPrincipal(username)); if (enableKerberos) { String spnServiceClass = kerberosUseHttpSpn ? "HTTP" : "WSMAN"; RegistryBuilder<AuthSchemeProvider> authSchemeRegistryBuilder = RegistryBuilder.create(); authSchemeRegistryBuilder.register(KERBEROS, new WsmanKerberosSchemeFactory(!kerberosAddPortToSpn, spnServiceClass, unmappedAddress, unmappedPort)); authSchemeRegistryBuilder.register(SPNEGO, new WsmanSPNegoSchemeFactory(!kerberosAddPortToSpn, spnServiceClass, unmappedAddress, unmappedPort)); httpclient.setDefaultAuthSchemeRegistry(authSchemeRegistryBuilder.build()); configureAuthentication(credentialsProvider, KERBEROS, new KerberosPrincipal(username)); configureAuthentication(credentialsProvider, SPNEGO, new KerberosPrincipal(username)); } httpclient.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(soTimeout).build()); httpclient.setDefaultRequestConfig( RequestConfig.custom().setAuthenticationEnabled(true).setConnectTimeout(connectionTimeout).build()); }
From source file:eu.esdihumboldt.hale.common.cache.Request.java
/** * Get the HTTP client for a given proxy * // ww w.ja v a2 s.co m * @param proxy the proxy * @return the client configured for the proxy */ private synchronized CloseableHttpClient getClient(Proxy proxy) { CloseableHttpClient client = clients.get(proxy); if (client == null) { HttpClientBuilder builder = ClientUtil.threadSafeHttpClientBuilder(); builder = ClientProxyUtil.applyProxy(builder, proxy); // set timeouts // determine from Oracle VM specific system properties, see // http://docs.oracle.com/javase/7/docs/technotes/guides/net/properties.html int connectTimeout; String cts = System.getProperty("sun.net.client.defaultConnectTimeout"); try { connectTimeout = Integer.parseInt(cts); } catch (Exception e) { // fall back to default connectTimeout = 10000; } int socketTimeout; String sts = System.getProperty("sun.net.client.defaultReadTimeout"); try { socketTimeout = Integer.parseInt(sts); } catch (Exception e) { // fall back to default socketTimeout = 20000; } // socket timeout /* * Unclear when this setting would apply (doc says for non-blocking * I/O operations), it does not seem to be applied for requests as * done in openStream (instead the value in * RequestConfig.socketTimeout is used) */ SocketConfig socketconfig = SocketConfig.custom().setSoTimeout(socketTimeout).build(); // connection and socket timeout RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout) .setConnectTimeout(connectTimeout).build(); client = builder.setDefaultRequestConfig(requestConfig).setDefaultSocketConfig(socketconfig).build(); clients.put(proxy, client); } return client; }
From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java
/** * Prepare asynchronous connection.//from w w w.j a v a 2 s.c o m * * @throws microsoft.exchange.webservices.data.EWSHttpException throws EWSHttpException */ public void prepareAsyncConnection() throws EWSHttpException { try { //ssl config HttpClientBuilder builder = HttpClients.custom(); builder.setConnectionManager(this.httpClientConnMng); builder.setSchemePortResolver(new DefaultSchemePortResolver()); EwsSSLProtocolSocketFactory factory = EwsSSLProtocolSocketFactory.build(trustManger); builder.setSSLSocketFactory(factory); builder.setSslcontext(factory.getContext()); //create the cookie store if (cookieStore == null) { cookieStore = new BasicCookieStore(); } builder.setDefaultCookieStore(cookieStore); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(getUserName(), getPassword(), "", getDomain())); builder.setDefaultCredentialsProvider(credsProvider); //fix socket config SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build(); builder.setDefaultSocketConfig(sc); RequestConfig.Builder rcBuilder = RequestConfig.custom(); rcBuilder.setConnectionRequestTimeout(getTimeout()); rcBuilder.setConnectTimeout(getTimeout()); rcBuilder.setSocketTimeout(getTimeout()); // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials ArrayList<String> authPrefs = new ArrayList<String>(); authPrefs.add(AuthSchemes.NTLM); rcBuilder.setTargetPreferredAuthSchemes(authPrefs); // builder.setDefaultRequestConfig(rcBuilder.build()); //HttpClientParams.setRedirecting(client.getParams(), isAllowAutoRedirect()); by default it follows redirects //create the client and execute requests client = builder.build(); httpPostReq = new HttpPost(getUrl().toString()); response = client.execute(httpPostReq); } catch (IOException e) { client = null; httpPostReq = null; throw new EWSHttpException("Unable to open connection to " + this.getUrl()); } catch (Exception e) { client = null; httpPostReq = null; e.printStackTrace(); throw new EWSHttpException("SSL problem " + this.getUrl()); } }
From source file:org.apache.hadoop.gateway.dispatch.DefaultHttpClientFactory.java
@Override public HttpClient createHttpClient(FilterConfig filterConfig) { HttpClientBuilder builder = null; GatewayConfig gatewayConfig = (GatewayConfig) filterConfig.getServletContext() .getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE); if (gatewayConfig != null && gatewayConfig.isMetricsEnabled()) { GatewayServices services = (GatewayServices) filterConfig.getServletContext() .getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE); MetricsService metricsService = services.getService(GatewayServices.METRICS_SERVICE); builder = metricsService.getInstrumented(HttpClientBuilder.class); } else {// w w w . j ava 2 s.c om builder = HttpClients.custom(); } if ("true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UseJaasCredentials()); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new KnoxSpnegoAuthSchemeFactory(true)).build(); builder = builder.setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCookieStore(new HadoopAuthCookieStore()) .setDefaultCredentialsProvider(credentialsProvider); } else { builder = builder.setDefaultCookieStore(new NoCookieStore()); } builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE); builder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE); builder.setRedirectStrategy(new NeverRedirectStrategy()); builder.setRetryHandler(new NeverRetryHandler()); int maxConnections = getMaxConnections(filterConfig); builder.setMaxConnTotal(maxConnections); builder.setMaxConnPerRoute(maxConnections); builder.setDefaultRequestConfig(getRequestConfig(filterConfig)); HttpClient client = builder.build(); return client; }
From source file:com.samebug.clients.search.api.client.RawClient.java
RawClient(@NotNull final Config config) { HttpClientBuilder httpBuilder = HttpClientBuilder.create(); requestConfigBuilder = RequestConfig.custom(); CredentialsProvider provider = new BasicCredentialsProvider(); requestConfigBuilder.setConnectTimeout(config.connectTimeout).setSocketTimeout(config.requestTimeout) .setConnectionRequestTimeout(500); try {/*from w w w . ja va 2 s.c o m*/ IdeHttpClientHelpers.ApacheHttpClient4.setProxyForUrlIfEnabled(requestConfigBuilder, config.serverRoot); IdeHttpClientHelpers.ApacheHttpClient4.setProxyCredentialsForUrlIfEnabled(provider, config.serverRoot); } catch (Throwable e) { // fallback to traditional proxy config for backward compatiblity try { final HttpConfigurable proxySettings = HttpConfigurable.getInstance(); final ProxyCredentialsFacade facade = new ProxyCredentialsFacade(proxySettings); if (proxySettings != null && proxySettings.USE_HTTP_PROXY && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)) { requestConfigBuilder.setProxy(new HttpHost(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT)); if (proxySettings.PROXY_AUTHENTICATION) { provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(facade.getLogin(), facade.getPassword())); } } } catch (Throwable ignored) { // if even that fails, we cannot do more } } defaultRequestConfig = requestConfigBuilder.build(); trackingConfig = requestConfigBuilder.setSocketTimeout(TrackingRequestTimeout_Millis).build(); List<BasicHeader> defaultHeaders = new ArrayList<BasicHeader>(); defaultHeaders.add(new BasicHeader("User-Agent", USER_AGENT)); if (config.apiKey != null) defaultHeaders.add(new BasicHeader("X-Samebug-ApiKey", config.apiKey)); if (config.workspaceId != null) defaultHeaders.add(new BasicHeader("X-Samebug-WorkspaceId", config.workspaceId.toString())); httpClient = httpBuilder.setDefaultRequestConfig(defaultRequestConfig).setMaxConnTotal(MaxConnections) .setMaxConnPerRoute(MaxConnections).setDefaultCredentialsProvider(provider) .setDefaultHeaders(defaultHeaders).build(); if (config.isApacheLoggingEnabled) enableApacheLogging(); }
From source file:org.bonitasoft.connectors.rest.RESTConnector.java
/** * Execute a given request/*from w ww .j a v a2 s.com*/ * * @param request The request to execute * @return The response of the executed request * @throws Exception any exception that might occur */ public void execute(final Request request) throws Exception { CloseableHttpClient httpClient = null; try { final URL url = request.getUrl(); final String urlHost = url.getHost(); final Builder requestConfigurationBuilder = RequestConfig.custom(); requestConfigurationBuilder.setConnectionRequestTimeout(CONNECTION_TIMEOUT); requestConfigurationBuilder.setRedirectsEnabled(request.isRedirect()); final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); setSSL(request.getSsl(), httpClientBuilder); setProxy(request.getProxy(), httpClientBuilder, requestConfigurationBuilder); setCookies(requestConfigurationBuilder, httpClientBuilder, request.getCookies(), urlHost); final RequestBuilder requestBuilder = getRequestBuilderFromMethod(request.getRestMethod()); requestBuilder.setVersion( new ProtocolVersion(HTTP_PROTOCOL, HTTP_PROTOCOL_VERSION_MAJOR, HTTP_PROTOCOL_VERSION_MINOR)); int urlPort = url.getPort(); if (url.getPort() == -1) { urlPort = url.getDefaultPort(); } final String urlProtocol = url.getProtocol(); final String urlStr = url.toString(); requestBuilder.setUri(urlStr); setHeaders(requestBuilder, request.getHeaders()); if (!HTTPMethod.GET.equals(HTTPMethod.valueOf(requestBuilder.getMethod()))) { final String body = request.getBody(); if (body != null) { requestBuilder.setEntity(new StringEntity(request.getBody(), request.getContentType())); } } final HttpContext httpContext = setAuthorizations(requestConfigurationBuilder, request.getAuthorization(), request.getProxy(), urlHost, urlPort, urlProtocol, httpClientBuilder); requestBuilder.setConfig(requestConfigurationBuilder.build()); httpClientBuilder.setDefaultRequestConfig(requestConfigurationBuilder.build()); final HttpUriRequest httpRequest = requestBuilder.build(); httpClient = httpClientBuilder.build(); final CloseableHttpResponse httpResponse = httpClient.execute(httpRequest, httpContext); LOGGER.fine("Request sent."); setOutputs(httpResponse, request); } finally { try { if (httpClient != null) { httpClient.close(); } } catch (final IOException ex) { logException(ex); } } }
From source file:org.codelibs.fess.crawler.extractor.impl.ApiExtractor.java
@PostConstruct public void init() { if (logger.isDebugEnabled()) { logger.debug("Initializing " + ApiExtractor.class.getName()); }/*w w w . j a v a 2 s . c o m*/ // httpclient final org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); final Integer connectionTimeoutParam = connectionTimeout; if (connectionTimeoutParam != null) { requestConfigBuilder.setConnectTimeout(connectionTimeoutParam); } final Integer soTimeoutParam = soTimeout; if (soTimeoutParam != null) { requestConfigBuilder.setSocketTimeout(soTimeoutParam); } // AuthSchemeFactory final RegistryBuilder<AuthSchemeProvider> authSchemeProviderBuilder = RegistryBuilder.create(); // @SuppressWarnings("unchecked") final Map<String, AuthSchemeProvider> factoryMap = authSchemeProviderMap; if (factoryMap != null) { for (final Map.Entry<String, AuthSchemeProvider> entry : factoryMap.entrySet()) { authSchemeProviderBuilder.register(entry.getKey(), entry.getValue()); } } // user agent if (StringUtil.isNotBlank(userAgent)) { httpClientBuilder.setUserAgent(userAgent); } // Authentication final Authentication[] siteCredentialList = new Authentication[0]; for (final Authentication authentication : siteCredentialList) { final AuthScope authScope = authentication.getAuthScope(); credentialsProvider.setCredentials(authScope, authentication.getCredentials()); final AuthScheme authScheme = authentication.getAuthScheme(); if (authScope.getHost() != null && authScheme != null) { final HttpHost targetHost = new HttpHost(authScope.getHost(), authScope.getPort()); authCache.put(targetHost, authScheme); } } httpClientContext.setAuthCache(authCache); httpClientContext.setCredentialsProvider(credentialsProvider); // Request Header final RequestHeader[] requestHeaders = { new RequestHeader("enctype", "multipart/form-data") }; for (final RequestHeader requestHeader : requestHeaders) { if (requestHeader.isValid()) { requestHeaderList.add(new BasicHeader(requestHeader.getName(), requestHeader.getValue())); } } final CloseableHttpClient closeableHttpClient = httpClientBuilder .setDefaultRequestConfig(requestConfigBuilder.build()).build(); if (!httpClientPropertyMap.isEmpty()) { final BeanDesc beanDesc = BeanDescFactory.getBeanDesc(closeableHttpClient.getClass()); for (final Map.Entry<String, Object> entry : httpClientPropertyMap.entrySet()) { final String propertyName = entry.getKey(); if (beanDesc.hasPropertyDesc(propertyName)) { final PropertyDesc propertyDesc = beanDesc.getPropertyDesc(propertyName); propertyDesc.setValue(closeableHttpClient, entry.getValue()); } else { logger.warn("DefaultHttpClient does not have " + propertyName + "."); } } } httpClient = closeableHttpClient; }