List of usage examples for org.apache.http.impl.client HttpClientBuilder setRoutePlanner
public final HttpClientBuilder setRoutePlanner(final HttpRoutePlanner routePlanner)
From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java
protected void setProxyHost(HttpClientBuilder httpClientBuilder) { if ((_proxyHostName == null) || _proxyHostName.equals("")) { return;/*from w w w . j av a 2 s .c o m*/ } HttpHost httpHost = new HttpHost(_proxyHostName, _proxyHostPort); HttpRoutePlanner httpRoutePlanner = new DefaultProxyRoutePlanner(httpHost); httpClientBuilder.setRoutePlanner(httpRoutePlanner); }
From source file:jp.co.ctc_g.jse.core.rest.springmvc.client.ProxyClientHttpRequestFactory.java
/** * ???????HttpClient????????// w w w .j a va2s. com * {@inheritDoc} */ @Override public void afterPropertiesSet() throws Exception { Assert.notNull(proxyHost, "(proxyHost)???"); Assert.notNull(proxyPort, "??(proxyPort)???"); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(maxTotal); connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute); HttpClientBuilder builder = HttpClients.custom(); builder.setConnectionManager(connectionManager); if (authentication) { Assert.notNull(username, "??true???????(username)???"); Assert.notNull(password, "??true?????(password)???"); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner( new HttpHost(proxyHost, Integer.parseInt(proxyPort))); builder.setRoutePlanner(routePlanner); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, Integer.parseInt(proxyPort)), new UsernamePasswordCredentials(username, password)); builder.setDefaultCredentialsProvider(credsProvider); } builder.setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(readTimeout).build()); CloseableHttpClient client = builder.build(); setHttpClient(client); }
From source file:org.tinymediamanager.scraper.util.TmmHttpClient.java
private static void setProxy(HttpClientBuilder httpClientBuilder) { HttpHost proxyHost = null;//w w w . j av a 2s.c o m if (StringUtils.isNotEmpty(Globals.settings.getProxyPort())) { proxyHost = new HttpHost(Globals.settings.getProxyHost(), Integer.parseInt(Globals.settings.getProxyPort())); } else { proxyHost = new HttpHost(Globals.settings.getProxyHost()); } // authenticate if (!StringUtils.isEmpty(Globals.settings.getProxyUsername()) && !StringUtils.isEmpty(Globals.settings.getProxyPassword())) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (Globals.settings.getProxyUsername().contains("\\")) { // use NTLM int offset = Globals.settings.getProxyUsername().indexOf("\\"); String domain = Globals.settings.getProxyUsername().substring(0, offset); String username = Globals.settings.getProxyUsername().substring(offset + 1, Globals.settings.getProxyUsername().length()); credentialsProvider.setCredentials(AuthScope.ANY, new NTCredentials(username, Globals.settings.getProxyPassword(), "", domain)); } else { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( Globals.settings.getProxyUsername(), Globals.settings.getProxyPassword())); } httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } // set proxy DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost); httpClientBuilder.setRoutePlanner(routePlanner); // try to get proxy settings from JRE - is probably added in HttpClient 4.3; fixed with 4.3.3 // (https://issues.apache.org/jira/browse/HTTPCLIENT-1457) // SystemDefaultCredentialsProvider credentialsProvider = new SystemDefaultCredentialsProvider(); // httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); // SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault()); // httpClientBuilder.setRoutePlanner(routePlanner); }
From source file:com.conwet.wirecloud.ide.WirecloudAPI.java
protected CloseableHttpClient createHttpClient(URL url) { HttpClientBuilder hcBuilder = HttpClients.custom(); IProxyService proxyService = getProxyService(); IProxyData[] proxyDataForHost;/* w w w . j av a 2 s . c om*/ try { proxyDataForHost = proxyService.select(url.toURI()); } catch (URISyntaxException e) { throw new AssertionError(e); } for (IProxyData iProxyData : proxyDataForHost) { HttpHost proxy = new HttpHost(iProxyData.getHost(), iProxyData.getPort(), iProxyData.getType()); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); hcBuilder.setRoutePlanner(routePlanner); } return hcBuilder.build(); }
From source file:nl.armatiek.xslweb.configuration.WebApp.java
public CloseableHttpClient getHttpClient() { if (httpClient == null) { PoolingHttpClientConnectionManager cm; if (Context.getInstance().getTrustAllCerts()) { try { SSLContextBuilder scb = SSLContexts.custom(); scb.loadTrustMaterial(null, new TrustStrategy() { @Override// ww w . j a v a 2s.co m public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = scb.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf) .register("http", new PlainConnectionSocketFactory()).build(); cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); } catch (Exception e) { logger.warn("Could not set HttpClient to trust all SSL certificates", e); cm = new PoolingHttpClientConnectionManager(); } } else { cm = new PoolingHttpClientConnectionManager(); } cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); HttpHost localhost = new HttpHost("localhost", 80); cm.setMaxPerRoute(new HttpRoute(localhost), 50); HttpClientBuilder builder = HttpClients.custom().setConnectionManager(cm); builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); builder.setDefaultCookieStore(new BasicCookieStore()); httpClient = builder.build(); } return httpClient; }
From source file:org.jenkinsci.plugins.newrelicnotifier.api.NewRelicClientImpl.java
private CloseableHttpClient getHttpClient(URI url) { HttpClientBuilder builder = HttpClientBuilder.create(); ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy; if (proxyConfig != null) { Proxy proxy = proxyConfig.createProxy(url.getHost()); if (proxy != null && proxy.type() == Proxy.Type.HTTP) { SocketAddress addr = proxy.address(); if (addr != null && addr instanceof InetSocketAddress) { InetSocketAddress proxyAddr = (InetSocketAddress) addr; HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort()); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost); builder = builder.setRoutePlanner(routePlanner); String proxyUser = proxyConfig.getUserName(); if (proxyUser != null) { String proxyPass = proxyConfig.getPassword(); CredentialsProvider cred = new BasicCredentialsProvider(); cred.setCredentials(new AuthScope(proxyHost), new UsernamePasswordCredentials(proxyUser, proxyPass)); builder = builder.setDefaultCredentialsProvider(cred) .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); }// w w w . j a v a2s. c om } } } return builder.build(); }
From source file:com.nominanuda.web.http.HttpCoreHelper.java
public HttpClient createClient(int maxConnPerRoute, long connTimeoutMillis, long soTimeoutMillis, @Nullable String proxyHostAnPort) { Registry<ConnectionSocketFactory> defaultRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", SSLConnectionSocketFactory.getSocketFactory()).build(); PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(defaultRegistry); connMgr.setDefaultMaxPerRoute(maxConnPerRoute); SocketConfig sCfg = SocketConfig.custom().setSoTimeout((int) soTimeoutMillis) .setSoTimeout((int) connTimeoutMillis).build(); connMgr.setDefaultSocketConfig(sCfg); HttpClientBuilder hcb = HttpClientBuilder.create(); hcb.setDefaultSocketConfig(sCfg).setConnectionManager(connMgr); if (proxyHostAnPort == null) { } else if ("jvm".equalsIgnoreCase(proxyHostAnPort)) { SystemDefaultRoutePlanner rp = new SystemDefaultRoutePlanner(ProxySelector.getDefault()); hcb.setRoutePlanner(rp); } else {/* w ww .j av a 2 s .c o m*/ String[] hostAndPort = proxyHostAnPort.split(":"); Check.illegalargument.assertTrue(hostAndPort.length < 3, "wrong hostAndPort:" + proxyHostAnPort); String host = hostAndPort[0]; int port = 80; if (hostAndPort.length > 1) { port = Integer.valueOf(hostAndPort[1]); } HttpHost proxy = new HttpHost(host, port); hcb.setProxy(proxy); } HttpClient httpClient = hcb.build(); return httpClient; }
From source file:net.yacy.cora.protocol.http.HTTPClient.java
private static HttpClientBuilder initClientBuilder() { final HttpClientBuilder builder = HttpClientBuilder.create(); builder.setConnectionManager(CONNECTION_MANAGER); builder.setDefaultRequestConfig(dfltReqConf); // UserAgent//w w w .jav a2 s . co m builder.setUserAgent(ClientIdentification.yacyInternetCrawlerAgent.userAgent); // remove retries; we expect connections to fail; therefore we should not retry //builder.disableAutomaticRetries(); // disable the cookiestore, cause this may cause segfaults and is not needed builder.setDefaultCookieStore(null); builder.disableCookieManagement(); // add custom keep alive strategy builder.setKeepAliveStrategy(customKeepAliveStrategy()); // ask for gzip builder.addInterceptorLast(new GzipRequestInterceptor()); // uncompress gzip builder.addInterceptorLast(new GzipResponseInterceptor()); // Proxy builder.setRoutePlanner(ProxySettings.RoutePlanner); builder.setDefaultCredentialsProvider(ProxySettings.CredsProvider); return builder; }
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.j a v a2 s .c o m*/ 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.mirth.connect.connectors.http.HttpDispatcher.java
@Override public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) { HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties; eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.WRITING)); String responseData = null;/*from w w w . j a v a2 s . co m*/ String responseError = null; String responseStatusMessage = null; Status responseStatus = Status.QUEUED; boolean validateResponse = false; CloseableHttpClient client = null; HttpRequestBase httpMethod = null; CloseableHttpResponse httpResponse = null; File tempFile = null; int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000); try { configuration.configureDispatcher(this, httpDispatcherProperties); long dispatcherId = getDispatcherId(); client = clients.get(dispatcherId); if (client == null) { BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager( socketFactoryRegistry.build()); httpClientConnectionManager .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build()); HttpClientBuilder clientBuilder = HttpClients.custom() .setConnectionManager(httpClientConnectionManager); HttpUtil.configureClientBuilder(clientBuilder); if (httpDispatcherProperties.isUseProxyServer()) { clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner()); } client = clientBuilder.build(); clients.put(dispatcherId, client); } URI hostURI = new URI(httpDispatcherProperties.getHost()); String host = hostURI.getHost(); String scheme = hostURI.getScheme(); int port = hostURI.getPort(); if (port == -1) { if (scheme.equalsIgnoreCase("https")) { port = 443; } else { port = 80; } } // Parse the content type field first, and then add the charset if needed ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType()); Charset charset = null; if (contentType.getCharset() == null) { charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset())); } else { charset = contentType.getCharset(); } if (httpDispatcherProperties.isMultipart()) { tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); } HttpHost target = new HttpHost(host, port, scheme); httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile, contentType, charset); HttpClientContext context = HttpClientContext.create(); // authentication if (httpDispatcherProperties.isUseAuthentication()) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(), httpDispatcherProperties.getPassword()); credsProvider.setCredentials(authScope, credentials); AuthCache authCache = new BasicAuthCache(); RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create(); if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) { logger.debug("using Digest authentication"); registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset)); if (httpDispatcherProperties.isUsePreemptiveAuthentication()) { processDigestChallenge(authCache, target, credentials, httpMethod, context); } } else { logger.debug("using Basic authentication"); registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset)); if (httpDispatcherProperties.isUsePreemptiveAuthentication()) { authCache.put(target, new BasicScheme()); } } context.setCredentialsProvider(credsProvider); context.setAuthSchemeRegistry(registryBuilder.build()); context.setAuthCache(authCache); logger.debug("using authentication with credentials: " + credentials); } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build(); context.setRequestConfig(requestConfig); // Set proxy information if (httpDispatcherProperties.isUseProxyServer()) { context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(), Integer.parseInt(httpDispatcherProperties.getProxyPort()))); } // execute the method logger.debug( "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString()); httpResponse = client.execute(target, httpMethod, context); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); logger.debug("received status code: " + statusCode); Map<String, List<String>> headers = new HashMap<String, List<String>>(); for (Header header : httpResponse.getAllHeaders()) { List<String> list = headers.get(header.getName()); if (list == null) { list = new ArrayList<String>(); headers.put(header.getName(), list); } list.add(header.getValue()); } connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString()); connectorMessage.getConnectorMap().put("responseHeaders", new MessageHeaders(new CaseInsensitiveMap(headers))); ContentType responseContentType = ContentType.get(httpResponse.getEntity()); if (responseContentType == null) { responseContentType = ContentType.TEXT_PLAIN; } Charset responseCharset = charset; if (responseContentType.getCharset() != null) { responseCharset = responseContentType.getCharset(); } final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes(); BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() { @Override public boolean isBinaryContentType(ContentType contentType) { return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType); } }; /* * First parse out the body of the HTTP response. Depending on the connector settings, * this could end up being a string encoded with the response charset, a byte array * representing the raw response payload, or a MimeMultipart object. */ Object responseBody = ""; // The entity could be null in certain cases such as 204 responses if (httpResponse.getEntity() != null) { // Only parse multipart if XML Body is selected and Parse Multipart is enabled if (httpDispatcherProperties.isResponseXmlBody() && httpDispatcherProperties.isResponseParseMultipart() && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) { responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(), responseContentType.toString())); } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) { responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent()); } else { responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset); } } /* * Now that we have the response body, we need to create the actual Response message * data. Depending on the connector settings this could be our custom serialized XML, a * Base64 string encoded from the raw response payload, or a string encoded from the * payload with the request charset. */ if (httpDispatcherProperties.isResponseXmlBody()) { responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody, responseContentType, httpDispatcherProperties.isResponseParseMultipart(), httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver); } else if (responseBody instanceof byte[]) { responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII"); } else { responseData = (String) responseBody; } validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse(); if (statusCode < HttpStatus.SC_BAD_REQUEST) { responseStatus = Status.SENT; } else { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Received error response from HTTP server.", null)); responseStatusMessage = ErrorMessageBuilder .buildErrorResponse("Received error response from HTTP server.", null); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData, null); } } catch (Exception e) { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Error connecting to HTTP server.", e)); responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), "Error connecting to HTTP server", e); } finally { try { HttpClientUtils.closeQuietly(httpResponse); // Delete temp files if we created them if (tempFile != null) { tempFile.delete(); tempFile = null; } } finally { eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.IDLE)); } } return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse); }