List of usage examples for org.apache.http.impl.client HttpClientBuilder setDefaultHeaders
public final HttpClientBuilder setDefaultHeaders(final Collection<? extends Header> defaultHeaders)
From source file:com.angelmmg90.consumerservicespotify.configuration.SpringWebConfig.java
@Bean public static RestTemplate getTemplate() throws IOException { if (template == null) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT), new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD)); Header[] h = new Header[3]; h[0] = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"); h[1] = new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + ACCESS_TOKEN); List<Header> headers = new ArrayList<>(Arrays.asList(h)); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.useSystemProperties(); clientBuilder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT)); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); clientBuilder.setDefaultHeaders(headers).build(); String SAMPLE_URL = "https://api.spotify.com/v1/users/yourUserName/playlists/7HHFd1tNiIFIwYwva5MTNv"; HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build(); clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); CloseableHttpClient client = clientBuilder.build(); client.execute(request);/*www . j a v a 2 s . c o m*/ HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setHttpClient(client); template = new RestTemplate(); template.setRequestFactory(factory); } return template; }
From source file:org.commonjava.util.jhttpc.auth.OAuth20BearerTokenAuthenticator.java
@Override public HttpClientBuilder decorateClientBuilder(final HttpClientBuilder builder) throws JHttpCException { final Header header = new BasicHeader(AUTHORIZATION_HEADER, String.format(BEARER_FORMAT, token)); return builder.setDefaultHeaders(Collections.<Header>singleton(header)); }
From source file:net.fischboeck.discogs.DiscogsClient.java
private void init() { HttpClientBuilder builder = HttpClients.custom(); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(REQUEST_TIMEOUT).build(); this.httpClient = builder.setDefaultHeaders(this.getDefaultHeaders()).setDefaultRequestConfig(requestConfig) .build();/* w ww . j a v a 2s. c o m*/ this.mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); }
From source file:basedefense.client.version.ModificationVersionCheck.java
public ModificationVersionCheck() { HttpClientBuilder builder = HttpClientBuilder.create(); builder.disableCookieManagement();//from w w w. j a v a2 s. c o m builder.disableRedirectHandling(); builder.setUserAgent(String.format(USER_AGENT_PATTERN, BaseDefenseModification.getInstance().getVersion())); builder.setDefaultHeaders(Lists.newArrayList(new BasicHeader("Accept", "application/vnd.github.v3+json"))); this.httpClient = builder.build(); }
From source file:com.nextdoor.bender.ipc.es.ElasticSearchTransportFactory.java
private HttpClientBuilder addUserPassAuth(HttpClientBuilder cb, BasicHttpAuthConfig auth) { /*// w w w . j a v a2s .c o m * Send auth via headers as the credentials provider method of auth does not work when using * SSL. */ byte[] encodedAuth = Base64.encodeBase64((auth.getUsername() + ":" + auth.getPassword()).getBytes()); String authHeader = "Basic " + new String(encodedAuth); cb.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.AUTHORIZATION, authHeader))); return cb; }
From source file:crawler.PageFetcher.java
public PageFetcher(CrawlConfig config) { super(config); RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false) .setCookieSpec(config.getCookiePolicy()).setRedirectsEnabled(false) .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout()) .build();//from w ww . j ava 2s . c o m RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create(); connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE); if (config.isIncludeHttpsPages()) { try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174 // By always trusting the ssl certificate SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, String authType) { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SniSSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); connRegistryBuilder.register("https", sslsf); } catch (Exception e) { logger.warn("Exception thrown while trying to register https"); logger.debug("Stacktrace", e); } } Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build(); connectionManager = new SniPoolingHttpClientConnectionManager(connRegistry); connectionManager.setMaxTotal(config.getMaxTotalConnections()); connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost()); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setDefaultRequestConfig(requestConfig); clientBuilder.setConnectionManager(connectionManager); clientBuilder.setUserAgent(config.getUserAgentString()); clientBuilder.setDefaultHeaders(config.getDefaultHeaders()); if (config.getProxyHost() != null) { if (config.getProxyUsername() != null) { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()), new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword())); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); } HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort()); clientBuilder.setProxy(proxy); logger.debug("Working through Proxy: {}", proxy.getHostName()); } httpClient = clientBuilder.build(); if ((config.getAuthInfos() != null) && !config.getAuthInfos().isEmpty()) { doAuthetication(config.getAuthInfos()); } if (connectionMonitorThread == null) { connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager); } connectionMonitorThread.start(); }
From source file:crawler.java.edu.uci.ics.crawler4j.fetcher.PageFetcher.java
public PageFetcher(CrawlConfig config) { super(config); RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false) .setCookieSpec(CookieSpecs.DEFAULT).setRedirectsEnabled(false) .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout()) .build();/*from w w w . j ava 2s .co m*/ RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create(); connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE); if (config.isIncludeHttpsPages()) { try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174 // By always trusting the ssl certificate SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, String authType) { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); connRegistryBuilder.register("https", sslsf); } catch (Exception e) { logger.warn("Exception thrown while trying to register https"); logger.debug("Stacktrace", e); } } Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build(); connectionManager = new PoolingHttpClientConnectionManager(connRegistry); connectionManager.setMaxTotal(config.getMaxTotalConnections()); connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost()); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setDefaultRequestConfig(requestConfig); clientBuilder.setConnectionManager(connectionManager); clientBuilder.setUserAgent(config.getUserAgentString()); clientBuilder.setDefaultHeaders(config.getDefaultHeaders()); if (config.getProxyHost() != null) { if (config.getProxyUsername() != null) { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()), new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword())); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); } HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort()); clientBuilder.setProxy(proxy); logger.debug("Working through Proxy: {}", proxy.getHostName()); } httpClient = clientBuilder.build(); if ((config.getAuthInfos() != null) && !config.getAuthInfos().isEmpty()) { doAuthetication(config.getAuthInfos()); } if (connectionMonitorThread == null) { connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager); } connectionMonitorThread.start(); }
From source file:org.jboss.tools.jmx.jolokia.JolokiaConnectionWrapper.java
protected J4pClient createJ4pClient() { CustomClientBuilder jb = new CustomClientBuilder() { @Override// www .j a va2 s. c o m public void clientBuilderAdditions(HttpClientBuilder builder) { Set<Header> defaultHeaders = headers.entrySet().stream() .map(entry -> new BasicHeader(entry.getKey(), entry.getValue())) .collect(Collectors.toSet()); builder.setDefaultHeaders(defaultHeaders); } @Override protected SSLConnectionSocketFactory createDefaultSSLConnectionSocketFactory() { if (ignoreSSLErrors) { try { final SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { new AcceptAllTrustManager() }, null); return new JolokiaSSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier()); } catch (NoSuchAlgorithmException e1) { Activator.pluginLog().logWarning(e1); } catch (KeyManagementException e) { Activator.pluginLog().logWarning(e); } } SSLContext sslcontext = SSLContexts.createSystemDefault(); X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier(); return new SSLConnectionSocketFactory(sslcontext, hostnameVerifier); } }; jb.url(url); return jb.build(); }
From source file:com.liferay.sync.engine.session.Session.java
public static HttpClientBuilder createHttpClientBuilder(boolean trustSelfSigned, int maxConnections) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.disableAutomaticRetries(); RequestConfig.Builder builder = RequestConfig.custom(); builder.setConnectTimeout(PropsValues.SYNC_HTTP_CONNECTION_TIMEOUT); if (maxConnections == Integer.MAX_VALUE) { builder.setSocketTimeout(PropsValues.SYNC_HTTP_SOCKET_TIMEOUT * 2); } else {/* w w w . ja v a 2 s . c om*/ builder.setSocketTimeout(PropsValues.SYNC_HTTP_SOCKET_TIMEOUT); } List<Header> headers = new ArrayList<>(2); Header syncBuildHeader = new BasicHeader("Sync-Build", String.valueOf(ReleaseInfo.getBuildNumber())); headers.add(syncBuildHeader); String syncDeviceType = null; if (OSDetector.isApple()) { syncDeviceType = "desktop-mac"; } else if (OSDetector.isLinux()) { syncDeviceType = "desktop-linux"; } else if (OSDetector.isWindows()) { syncDeviceType = "desktop-windows"; } Header syncDeviceTypeHeader = new BasicHeader("Sync-Device", syncDeviceType); headers.add(syncDeviceTypeHeader); httpClientBuilder.setDefaultHeaders(headers); httpClientBuilder.setDefaultRequestConfig(builder.build()); httpClientBuilder.setMaxConnPerRoute(maxConnections); httpClientBuilder.setMaxConnTotal(maxConnections); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClientBuilder.setRoutePlanner(getHttpRoutePlanner()); try { if (trustSelfSigned) { httpClientBuilder.setSSLSocketFactory(_getTrustingSSLSocketFactory()); } else { httpClientBuilder.setSSLSocketFactory(_getDefaultSSLSocketFactory()); } } catch (Exception e) { _logger.error(e.getMessage(), e); } return httpClientBuilder; }
From source file:com.rabbitmq.http.client.Client.java
private HttpComponentsClientHttpRequestFactory getRequestFactory(final URL url, final String username, final String password, final SSLConnectionSocketFactory sslConnectionSocketFactory, final SSLContext sslContext) throws MalformedURLException { String theUser = username;//from w w w . j av a 2 s .c om String thePassword = password; String userInfo = url.getUserInfo(); if (userInfo != null && theUser == null) { String[] userParts = userInfo.split(":"); if (userParts.length > 0) { theUser = userParts[0]; } if (userParts.length > 1) { thePassword = userParts[1]; } } final HttpClientBuilder bldr = HttpClientBuilder.create() .setDefaultCredentialsProvider(getCredentialsProvider(url, theUser, thePassword)); bldr.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"))); if (sslConnectionSocketFactory != null) { bldr.setSSLSocketFactory(sslConnectionSocketFactory); } if (sslContext != null) { bldr.setSslcontext(sslContext); } HttpClient httpClient = bldr.build(); // RabbitMQ HTTP API currently does not support challenge/response for PUT methods. AuthCache authCache = new BasicAuthCache(); BasicScheme basicScheme = new BasicScheme(); authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicScheme); final HttpClientContext ctx = HttpClientContext.create(); ctx.setAuthCache(authCache); return new HttpComponentsClientHttpRequestFactory(httpClient) { @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { return ctx; } }; }