use of org.apache.http.config.ConnectionConfig in project apn-proxy by apn-proxy.
the class TestProxyWithHttpClient method test.
private void test(String uri, int exceptCode, String exceptHeaderName, String exceptHeaderValue) {
ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(2000);
cm.setDefaultMaxPerRoute(40);
cm.setDefaultConnectionConfig(connectionConfig);
CloseableHttpClient httpClient = HttpClients.custom().setUserAgent("Mozilla/5.0 xx-dev-web-common httpclient/4.x").setConnectionManager(cm).disableContentCompression().disableCookieManagement().build();
HttpHost proxy = new HttpHost("127.0.0.1", ApnProxyConfig.getConfig().getPort());
RequestConfig config = RequestConfig.custom().setProxy(proxy).setExpectContinueEnabled(true).setConnectionRequestTimeout(5000).setConnectTimeout(10000).setSocketTimeout(10000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
HttpGet request = new HttpGet(uri);
request.setConfig(config);
try {
CloseableHttpResponse httpResponse = httpClient.execute(request);
Assert.assertEquals(exceptCode, httpResponse.getStatusLine().getStatusCode());
if (StringUtils.isNotBlank(exceptHeaderName) && StringUtils.isNotBlank(exceptHeaderValue)) {
Assert.assertEquals(exceptHeaderValue, httpResponse.getFirstHeader(exceptHeaderName).getValue());
}
ResponseHandler<String> responseHandler = new BasicResponseHandler();
responseHandler.handleResponse(httpResponse);
httpResponse.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
use of org.apache.http.config.ConnectionConfig in project fabric8 by jboss-fuse.
the class HttpClients method createConnManager.
private static PoolingHttpClientConnectionManager createConnManager(PropertyResolver resolver, String pid) {
boolean SSL_INSECURE = getBoolean(resolver, "maven.wagon.http.ssl.insecure", !getBoolean(resolver, pid + "certificateCheck", false));
boolean IGNORE_SSL_VALIDITY_DATES = getBoolean(resolver, "maven.wagon.http.ssl.ignore.validity.dates", false);
boolean SSL_ALLOW_ALL = getBoolean(resolver, "maven.wagon.http.ssl.allowall", !getBoolean(resolver, pid + "certificateCheck", false));
boolean PERSISTENT_POOL = getBoolean(resolver, "maven.wagon.http.pool", true);
int MAX_CONN_PER_ROUTE = getInteger(resolver, "maven.wagon.httpconnectionManager.maxPerRoute", 20);
int MAX_CONN_TOTAL = getInteger(resolver, "maven.wagon.httpconnectionManager.maxTotal", 40);
String sslProtocolsStr = getProperty(resolver, "https.protocols", null);
String cipherSuitesStr = getProperty(resolver, "https.cipherSuites", null);
String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null;
String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null;
SSLConnectionSocketFactory sslConnectionSocketFactory;
if (SSL_INSECURE) {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build();
sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites, SSL_ALLOW_ALL ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier());
} catch (Exception ex) {
throw new SSLInitializationException(ex.getMessage(), ex);
}
} else {
sslConnectionSocketFactory = new SSLConnectionSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites, new DefaultHostnameVerifier());
}
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", sslConnectionSocketFactory).build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
if (PERSISTENT_POOL) {
connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE);
connManager.setMaxTotal(MAX_CONN_TOTAL);
} else {
connManager.setMaxTotal(1);
}
boolean soKeepAlive = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_KEEPALIVE, false);
int soLinger = getInteger(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_LINGER, -1);
boolean soReuseAddress = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_REUSEADDRESS, false);
boolean soTcpNoDelay = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_TCP_NODELAY, true);
// int soTimeout = getInteger( resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_TIMEOUT, 0 );
SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(// default false
soKeepAlive).setSoLinger(// default -1
soLinger).setSoReuseAddress(// default false
soReuseAddress).setTcpNoDelay(// default true
soTcpNoDelay).setSoTimeout(// default 0, but set in org.apache.http.impl.conn.CPoolProxy.setSocketTimeout()
0).build();
connManager.setDefaultSocketConfig(socketConfig);
int bufferSize = getInteger(resolver, pid + ServiceConstants.PROPERTY_CONNECTION_BUFFER_SIZE, 8192);
ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(// default 8192
bufferSize).setFragmentSizeHint(// default 'buffer size'
bufferSize).build();
connManager.setDefaultConnectionConfig(connectionConfig);
return connManager;
}
use of org.apache.http.config.ConnectionConfig in project cxf by apache.
the class AsyncHTTPConduitFactory method setupNIOClient.
public synchronized void setupNIOClient(HTTPClientPolicy clientPolicy) throws IOReactorException {
if (client != null) {
return;
}
IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(ioThreadCount).setSelectInterval(selectInterval).setInterestOpQueued(interestOpQueued).setSoLinger(soLinger).setSoTimeout(soTimeout).setSoKeepAlive(soKeepalive).setTcpNoDelay(tcpNoDelay).build();
Registry<SchemeIOSessionStrategy> ioSessionFactoryRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE).register("https", SSLIOSessionStrategy.getSystemDefaultStrategy()).build();
ManagedNHttpClientConnectionFactory connectionFactory = new ManagedNHttpClientConnectionFactory();
DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(config);
connectionManager = new PoolingNHttpClientConnectionManager(ioreactor, connectionFactory, ioSessionFactoryRegistry, DefaultSchemePortResolver.INSTANCE, SystemDefaultDnsResolver.INSTANCE, connectionTTL, TimeUnit.MILLISECONDS);
connectionManager.setDefaultMaxPerRoute(maxPerRoute);
connectionManager.setMaxTotal(maxConnections);
ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(clientPolicy.getChunkLength() > 0 ? clientPolicy.getChunkLength() : 16332).build();
connectionManager.setDefaultConnectionConfig(connectionConfig);
RedirectStrategy redirectStrategy = new RedirectStrategy() {
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return false;
}
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return null;
}
};
HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom().setConnectionManager(connectionManager).setRedirectStrategy(redirectStrategy).setDefaultCookieStore(new BasicCookieStore() {
private static final long serialVersionUID = 1L;
public void addCookie(Cookie cookie) {
}
});
adaptClientBuilder(httpAsyncClientBuilder);
client = httpAsyncClientBuilder.build();
// Start the client thread
client.start();
// Always start the idle checker thread to validate pending requests and
// use the ConnectionMaxIdle to close the idle connection
new CloseIdleConnectionThread(connectionManager, client).start();
}
use of org.apache.http.config.ConnectionConfig in project portal by ixinportal.
the class HttpAsyncClientUtil method createAsyncClient.
public CloseableHttpAsyncClient createAsyncClient(boolean proxy) throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, MalformedChallengeException, IOReactorException {
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
SSLContext sslcontext = SSLContexts.createDefault();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
// 设置协议http和https对应的处理socket链接工厂的对象
Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE).register("https", new SSLIOSessionStrategy(sslcontext)).build();
// 配置io线程
IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setIoThreadCount(Runtime.getRuntime().availableProcessors()).build();
// 设置连接池大小
ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
PoolingNHttpClientConnectionManager conMgr = new PoolingNHttpClientConnectionManager(ioReactor, null, sessionStrategyRegistry, null);
if (poolSize > 0) {
conMgr.setMaxTotal(poolSize);
}
if (maxPerRoute > 0) {
conMgr.setDefaultMaxPerRoute(maxPerRoute);
} else {
conMgr.setDefaultMaxPerRoute(10);
}
ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).build();
Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.BASIC, new BasicSchemeFactory()).register(AuthSchemes.DIGEST, new DigestSchemeFactory()).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()).register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();
conMgr.setDefaultConnectionConfig(connectionConfig);
if (proxy) {
return HttpAsyncClients.custom().setConnectionManager(conMgr).setDefaultCredentialsProvider(credentialsProvider).setDefaultAuthSchemeRegistry(authSchemeRegistry).setProxy(new HttpHost(host, port)).setDefaultCookieStore(new BasicCookieStore()).setDefaultRequestConfig(requestConfig).build();
} else {
return HttpAsyncClients.custom().setConnectionManager(conMgr).setDefaultCredentialsProvider(credentialsProvider).setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCookieStore(new BasicCookieStore()).build();
}
}
use of org.apache.http.config.ConnectionConfig in project sagacity-sqltoy by chenrenfei.
the class ElasticEndpoint method initRestClient.
/**
* @param restClient
* the restClient to set
*/
public void initRestClient() {
if (StringUtil.isBlank(this.getUrl()))
return;
if (restClient == null) {
String splitSign = ";";
if (this.getUrl().indexOf(";") == -1)
splitSign = ",";
String[] urls = this.getUrl().split(splitSign);
// 当为单一地址时使用httpclient直接调用
if (urls.length < 2)
return;
List<HttpHost> hosts = new ArrayList<HttpHost>();
for (String urlStr : urls) {
try {
if (StringUtil.isNotBlank(urlStr)) {
URL url = new java.net.URL(urlStr.trim());
hosts.add(new HttpHost(url.getHost(), url.getPort(), url.getProtocol()));
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
if (!hosts.isEmpty()) {
HttpHost[] hostAry = new HttpHost[hosts.size()];
hosts.toArray(hostAry);
RestClientBuilder builder = RestClient.builder(hostAry);
final ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Charset.forName(this.charset == null ? "UTF-8" : this.charset)).build();
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(this.requestTimeout).setConnectTimeout(this.connectTimeout).setSocketTimeout(this.socketTimeout).build();
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
final boolean hasCrede = (StringUtil.isNotBlank(this.getUsername()) && StringUtil.isNotBlank(getPassword())) ? true : false;
// 凭据提供器
if (hasCrede) {
credsProvider.setCredentials(AuthScope.ANY, // 认证用户名和密码
new UsernamePasswordCredentials(getUsername(), getPassword()));
}
builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.setDefaultConnectionConfig(connectionConfig).setDefaultRequestConfig(requestConfig);
if (hasCrede)
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
return httpClientBuilder;
}
});
restClient = builder.build();
}
}
}
Aggregations