Search in sources :

Example 1 with ConnectionConfig

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);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpHost(org.apache.http.HttpHost) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) IOException(java.io.IOException) ConnectionConfig(org.apache.http.config.ConnectionConfig) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 2 with ConnectionConfig

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;
}
Also used : SocketConfig(org.apache.http.config.SocketConfig) RelaxedTrustStrategy(org.apache.maven.wagon.providers.http.RelaxedTrustStrategy) SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLInitializationException(org.apache.http.conn.ssl.SSLInitializationException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier) SSLInitializationException(org.apache.http.conn.ssl.SSLInitializationException) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) ConnectionConfig(org.apache.http.config.ConnectionConfig)

Example 3 with ConnectionConfig

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();
}
Also used : HttpRequest(org.apache.http.HttpRequest) Cookie(org.apache.http.cookie.Cookie) SchemeIOSessionStrategy(org.apache.http.nio.conn.SchemeIOSessionStrategy) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) ManagedNHttpClientConnectionFactory(org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionFactory) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) IOReactorConfig(org.apache.http.impl.nio.reactor.IOReactorConfig) DefaultConnectingIOReactor(org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) RedirectStrategy(org.apache.http.client.RedirectStrategy) PoolingNHttpClientConnectionManager(org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager) ConnectionConfig(org.apache.http.config.ConnectionConfig)

Example 4 with ConnectionConfig

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();
    }
}
Also used : ConnectingIOReactor(org.apache.http.nio.reactor.ConnectingIOReactor) DefaultConnectingIOReactor(org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor) RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SchemeIOSessionStrategy(org.apache.http.nio.conn.SchemeIOSessionStrategy) SSLIOSessionStrategy(org.apache.http.nio.conn.ssl.SSLIOSessionStrategy) SSLContext(javax.net.ssl.SSLContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) IOReactorConfig(org.apache.http.impl.nio.reactor.IOReactorConfig) DefaultConnectingIOReactor(org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpHost(org.apache.http.HttpHost) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) PoolingNHttpClientConnectionManager(org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager) ConnectionConfig(org.apache.http.config.ConnectionConfig)

Example 5 with ConnectionConfig

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();
        }
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) MalformedURLException(java.net.MalformedURLException) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) ArrayList(java.util.ArrayList) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) URL(java.net.URL) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) HttpHost(org.apache.http.HttpHost) ConnectionConfig(org.apache.http.config.ConnectionConfig)

Aggregations

ConnectionConfig (org.apache.http.config.ConnectionConfig)9 HttpHost (org.apache.http.HttpHost)5 RequestConfig (org.apache.http.client.config.RequestConfig)5 SSLContext (javax.net.ssl.SSLContext)4 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)4 CredentialsProvider (org.apache.http.client.CredentialsProvider)4 SocketConfig (org.apache.http.config.SocketConfig)4 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)4 HttpResponse (org.apache.http.HttpResponse)3 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)3 PoolingNHttpClientConnectionManager (org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager)3 DefaultConnectingIOReactor (org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor)3 IOReactorConfig (org.apache.http.impl.nio.reactor.IOReactorConfig)3 SchemeIOSessionStrategy (org.apache.http.nio.conn.SchemeIOSessionStrategy)3 IOException (java.io.IOException)2 HostnameVerifier (javax.net.ssl.HostnameVerifier)2 HttpRequest (org.apache.http.HttpRequest)2 AuthCache (org.apache.http.client.AuthCache)2 BasicScheme (org.apache.http.impl.auth.BasicScheme)2 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)2