List of usage examples for org.apache.http.impl.client HttpClientBuilder setUserAgent
public final HttpClientBuilder setUserAgent(final String userAgent)
From source file:org.neo4j.jdbc.http.driver.CypherExecutor.java
/** * Default constructor.//from w ww .j a v a 2 s .co m * * @param host Hostname of the Neo4j instance. * @param port HTTP port of the Neo4j instance. * @param secure If the connection used SSL. * @param properties Properties of the url connection. */ public CypherExecutor(String host, Integer port, Boolean secure, Properties properties) throws SQLException { this.secure = secure; // Create the http client builder HttpClientBuilder builder = HttpClients.custom(); // Adding authentication to the http client if needed CredentialsProvider credentialsProvider = getCredentialsProvider(host, port, properties); if (credentialsProvider != null) builder.setDefaultCredentialsProvider(credentialsProvider); // Setting user-agent String userAgent = properties.getProperty("useragent"); builder.setUserAgent("Neo4j JDBC Driver" + (userAgent != null ? " via " + userAgent : "")); // Create the http client this.http = builder.build(); // Create the url endpoint this.transactionUrl = createTransactionUrl(host, port, secure); // Setting autocommit this.setAutoCommit(Boolean.valueOf(properties.getProperty("autoCommit", "true"))); }
From source file:de.taimos.httputils.HTTPRequest.java
private HttpResponse execute(final HttpUriRequest req) { final HttpClientBuilder builder = HttpClientBuilder.create(); final Builder reqConfig = RequestConfig.custom(); if (this.timeout != null) { reqConfig.setConnectTimeout(this.timeout); }/* ww w .j a v a 2s. c o m*/ reqConfig.setRedirectsEnabled(this.followRedirect); builder.setDefaultRequestConfig(reqConfig.build()); if ((this.userAgent != null) && !this.userAgent.isEmpty()) { builder.setUserAgent(this.userAgent); } try { final CloseableHttpClient httpclient = builder.build(); // if request has data populate body if (req instanceof HttpEntityEnclosingRequestBase) { final HttpEntityEnclosingRequestBase entityBase = (HttpEntityEnclosingRequestBase) req; entityBase.setEntity(new StringEntity(this.body, "UTF-8")); } // Set headers final Set<Entry<String, List<String>>> entrySet = this.headers.entrySet(); for (final Entry<String, List<String>> entry : entrySet) { final List<String> list = entry.getValue(); for (final String string : list) { req.addHeader(entry.getKey(), string); } } final HttpResponse response = httpclient.execute(req); return response; } catch (final ClientProtocolException e) { throw new RuntimeException(e); } catch (final IOException e) { throw new RuntimeException(e); } }
From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java
private CloseableHttpClient createHttpClient(ServerInfo serverInfo) { HttpClientBuilder builder = (useBuiltinWindowsAuthentication(serverInfo)) ? WinHttpClients.custom() : HttpClients.custom();//from www .ja v a 2 s . co m HttpClientConnectionManager connMgr = createConnectionManagerIfNecessary(); if (connMgr != null) { builder.setConnectionManager(connMgr); } builder.setUserAgent(userAgent); builder.useSystemProperties(); return builder.build(); }
From source file:synapticloop.scaleway.api.ScalewayApiClient.java
/** * Instantiate a new API Client for the Scaleway API Provider, each API * client points to a specific Region. Once this region is set, it cannot * be changed. Instead instantiate a new API client for the new region, * * @param accessToken the access token that is authorised to invoke the API - * see the credentials section: <a href="https://cloud.scaleway.com/#/credentials">https://cloud.scaleway.com/#/credentials</a> * for access tokens//from w w w. ja v a2 s . c om * @param region the scaleway datacentre region that this API points to (see * {@link Region} for all of the regions available at the moment) */ public ScalewayApiClient(String accessToken, Region region) { this.accessToken = accessToken; this.region = region; this.computeUrl = String.format(Constants.COMPUTE_URL, region); HttpClientBuilder httpBuilder = HttpClients.custom(); httpBuilder.setUserAgent(Constants.USER_AGENT); this.httpclient = httpBuilder.build(); Version currentJacksonVersion = new ObjectMapper().version(); Version earliestSupportedVersion = new Version(2, 8, 7, null, currentJacksonVersion.getGroupId(), currentJacksonVersion.getArtifactId()); int versionCompared = currentJacksonVersion.compareTo(earliestSupportedVersion); if (versionCompared < 0) { LOGGER.error("Jackson version: {}, version compared: {}", currentJacksonVersion.toString(), versionCompared); throw new RuntimeException( "Sorry, scaleway-api-client requires Jackson version 2.8.7 due to bugs in earlier versions."); } }
From source file:org.rundeck.api.ApiCall.java
/** * Instantiate a new {@link HttpClient} instance, configured to accept all SSL certificates * * @return an {@link HttpClient} instance - won't be null *///w ww. ja va2s.c o m private CloseableHttpClient instantiateHttpClient() { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().useSystemProperties(); // configure user-agent httpClientBuilder.setUserAgent("Rundeck API Java Client " + client.getApiVersion()); if (client.isSslHostnameVerifyAllowAll()) { httpClientBuilder.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } if (client.isSslCertificateTrustAllowSelfSigned()) { // configure SSL try { httpClientBuilder.setSslcontext( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } } if (client.isSystemProxyEnabled()) { // configure proxy (use system env : http.proxyHost / http.proxyPort) httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); } // in case of token-based authentication, add the correct HTTP header to all requests via an interceptor httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { if (client.getToken() != null) { request.addHeader(AUTH_TOKEN_HEADER, client.getToken()); //System.out.println("httpClient adding token header"); } else if (client.getSessionID() != null) { request.addHeader(COOKIE_HEADER, "JSESSIONID=" + client.getSessionID()); //System.out.println("httpClient adding session header, sessionID="+client.getSessionID()); } } }); return httpClientBuilder.build(); }
From source file:it.larusba.neo4j.jdbc.http.driver.CypherExecutor.java
/** * Default constructor./*from w ww . j a va 2s .c om*/ * * @param host Hostname of the Neo4j instance. * @param port HTTP port of the Neo4j instance. * @param properties Properties of the url connection. * @throws SQLException */ public CypherExecutor(String host, Integer port, Properties properties) throws SQLException { // Create the http client builder HttpClientBuilder builder = HttpClients.custom(); // Adding authentication to the http client if needed if (properties.containsKey("user") && properties.containsKey("password")) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials( properties.get("user").toString(), properties.get("password").toString())); builder.setDefaultCredentialsProvider(credsProvider); } // Setting user-agent StringBuilder sb = new StringBuilder(); sb.append("Neo4j JDBC Driver"); if (properties.containsKey("userAgent")) { sb.append(" via "); sb.append(properties.getProperty("userAgent")); } builder.setUserAgent(sb.toString()); // Create the http client this.http = builder.build(); // Create the url endpoint StringBuffer sbEndpoint = new StringBuffer(); sbEndpoint.append("http://").append(host).append(":").append(port).append("/db/data/transaction"); this.transactionUrl = sbEndpoint.toString(); // Setting autocommit this.setAutoCommit(Boolean.valueOf(properties.getProperty("autoCommit", "true"))); }
From source file:com.ibm.og.client.ApacheClient.java
private CloseableHttpClient createClient() { final HttpClientBuilder builder = HttpClients.custom(); if (this.userAgent != null) { builder.setUserAgent(this.userAgent); }// w w w. j ava 2s . co m // Some authentication implementations add Content-Length or Transfer-Encoding headers as a part // of their authentication algorithm; remove them here so that the default interceptors do not // throw a ProtocolException // @see RequestContent interceptor builder.addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { request.removeHeaders(HTTP.TRANSFER_ENCODING); request.removeHeaders(HTTP.CONTENT_LEN); } }); return builder.setRequestExecutor(new HttpRequestExecutor(this.waitForContinue)) .setConnectionManager(createConnectionManager()) // TODO investigate ConnectionConfig, particularly bufferSize and fragmentSizeHint // TODO defaultCredentialsProvider and defaultAuthSchemeRegistry for pre/passive auth? .setConnectionReuseStrategy(createConnectionReuseStrategy()) .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE).disableConnectionState() .disableCookieManagement().disableContentCompression().disableAuthCaching() .setRetryHandler(new CustomHttpRequestRetryHandler(this.retryCount, this.requestSentRetry)) .setRedirectStrategy(new CustomRedirectStrategy()).setDefaultRequestConfig(createRequestConfig()) .evictExpiredConnections() .evictIdleConnections(Long.valueOf(this.maxIdleTime), TimeUnit.MILLISECONDS).build(); }
From source file:org.codelibs.fess.crawler.extractor.impl.ApiExtractor.java
@PostConstruct public void init() { if (logger.isDebugEnabled()) { logger.debug("Initializing " + ApiExtractor.class.getName()); }//from w ww .j a v a 2 s.co 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; }
From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java
@Override public HttpClient createHTTPClient(String userAgent) { HttpClientBuilder builder = HttpClientBuilder.create(); builder.setSslcontext(createSSLContext()); builder.setSchemePortResolver(createSchemePortResolver()); builder.setDefaultRequestConfig(createRequestConfig()); builder.setProxy(createProxy());/*from w w w . j a v a2 s .com*/ builder.setDefaultCredentialsProvider(createCredentialsProvider()); builder.setDefaultConnectionConfig(createConnectionConfig()); builder.setUserAgent(userAgent); builder.setMaxConnTotal(maxConnections); //builder.setMaxConnPerRoute(maxConnPerRoute) buildCustomHttpClient(builder); //TODO Put in place a more permanent solution to the following //Fix GitHub #17 start RedirectStrategy strategy = createRedirectStrategy(); if (strategy == null) { strategy = LaxRedirectStrategy.INSTANCE; } builder.setRedirectStrategy(new TargetURLRedirectStrategy(strategy)); //Fix end HttpClient httpClient = builder.build(); if (AUTH_METHOD_FORM.equalsIgnoreCase(authMethod)) { authenticateUsingForm(httpClient); } return httpClient; }