Java Code Examples for org.apache.http.params.HttpConnectionParams#setTcpNoDelay()

The following examples show how to use org.apache.http.params.HttpConnectionParams#setTcpNoDelay() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpSendClientFactory.java    From PoseidonX with Apache License 2.0 6 votes vote down vote up
/**
 * 创建一个{@link HttpSendClient} 实例
 * <p>
 * 多态
 * 
 * @return
 */
public HttpSendClient newHttpSendClient() {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeOut());
    HttpConnectionParams.setSoTimeout(params, getSoTimeOut());
    // HttpConnectionParams.setLinger(params, 1);

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    // 解释: 握手的目的,是为了允许客户端在发送请求内容之前,判断源服务器是否愿意接受请求(基于请求头部)。
    // Expect:100-Continue握手需谨慎使用,因为遇到不支持HTTP/1.1协议的服务器或者代理时会引起问题。
    // 默认开启
    // HttpProtocolParams.setUseExpectContinue(params, false);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, getSocketBufferSize());

    ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager();
    threadSafeClientConnManager.setMaxTotal(getMaxTotalConnections());
    threadSafeClientConnManager.setDefaultMaxPerRoute(getDefaultMaxPerRoute());

    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(getRetryCount(), false);

    DefaultHttpClient httpClient = new DefaultHttpClient(threadSafeClientConnManager, params);
    httpClient.setHttpRequestRetryHandler(retryHandler);
    return new HttpSendClient(httpClient);
}
 
Example 2
Source File: MainActivity.java    From android-advanced-light with MIT License 6 votes vote down vote up
/**
 * 设置默认请求参数,并返回HttpClient
 *
 * @return HttpClient
 */
private HttpClient createHttpClient() {
    HttpParams mDefaultHttpParams = new BasicHttpParams();
    //设置连接超时
    HttpConnectionParams.setConnectionTimeout(mDefaultHttpParams, 15000);
    //设置请求超时
    HttpConnectionParams.setSoTimeout(mDefaultHttpParams, 15000);
    HttpConnectionParams.setTcpNoDelay(mDefaultHttpParams, true);
    HttpProtocolParams.setVersion(mDefaultHttpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(mDefaultHttpParams, HTTP.UTF_8);
    //持续握手
    HttpProtocolParams.setUseExpectContinue(mDefaultHttpParams, true);
    HttpClient mHttpClient = new DefaultHttpClient(mDefaultHttpParams);
    return mHttpClient;

}
 
Example 3
Source File: HttpEngine.java    From letv with Apache License 2.0 6 votes vote down vote up
private HttpParams createHttpParams() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, false);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(3));
    ConnManagerParams.setMaxTotalConnections(params, 3);
    ConnManagerParams.setTimeout(params, 1000);
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    HttpClientParams.setRedirecting(params, false);
    return params;
}
 
Example 4
Source File: PoolingClientConnectionManager.java    From letv with Apache License 2.0 6 votes vote down vote up
public static HttpClient get() {
    HttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, 3000);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(30));
    ConnManagerParams.setMaxTotalConnections(httpParams, 30);
    HttpClientParams.setRedirecting(httpParams, true);
    HttpProtocolParams.setUseExpectContinue(httpParams, true);
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
    HttpConnectionParams.setSoTimeout(httpParams, 2000);
    HttpConnectionParams.setConnectionTimeout(httpParams, 2000);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme(IDataSource.SCHEME_HTTP_TAG, PlainSocketFactory.getSocketFactory(), 80));
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        schemeRegistry.register(new Scheme(IDataSource.SCHEME_HTTPS_TAG, sf, 443));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
}
 
Example 5
Source File: HttpClientFactory.java    From NetEasyNews with GNU General Public License v3.0 6 votes vote down vote up
private static HttpParams createHttpParams() {
	final HttpParams params = new BasicHttpParams();
	// 设置是否启用旧连接检查,默认是开启的。关闭这个旧连接检查可以提高一点点性能,但是增加了I/O错误的风险(当服务端关闭连接时)。
	// 开启这个选项则在每次使用老的连接之前都会检查连接是否可用,这个耗时大概在15-30ms之间
	HttpConnectionParams.setStaleCheckingEnabled(params, false);
	HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);// 设置链接超时时间
	HttpConnectionParams.setSoTimeout(params, TIMEOUT);// 设置socket超时时间
	HttpConnectionParams.setSocketBufferSize(params, SOCKET_BUFFER_SIZE);// 设置缓存大小
	HttpConnectionParams.setTcpNoDelay(params, true);// 是否不使用延迟发送(true为不延迟)
	HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // 设置协议版本
	HttpProtocolParams.setUseExpectContinue(params, true);// 设置异常处理机制
	HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);// 设置编码
	HttpClientParams.setRedirecting(params, false);// 设置是否采用重定向

	ConnManagerParams.setTimeout(params, TIMEOUT);// 设置超时
	ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(MAX_CONNECTIONS));// 多线程最大连接数
	ConnManagerParams.setMaxTotalConnections(params, 10); // 多线程总连接数
	return params;
}
 
Example 6
Source File: AsyncHttpClient.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
public AsyncHttpClient(SchemeRegistry schemeregistry)
{
    a = 10;
    b = 10000;
    h = true;
    BasicHttpParams basichttpparams = new BasicHttpParams();
    ConnManagerParams.setTimeout(basichttpparams, b);
    ConnManagerParams.setMaxConnectionsPerRoute(basichttpparams, new ConnPerRouteBean(a));
    ConnManagerParams.setMaxTotalConnections(basichttpparams, 10);
    HttpConnectionParams.setSoTimeout(basichttpparams, b);
    HttpConnectionParams.setConnectionTimeout(basichttpparams, b);
    HttpConnectionParams.setTcpNoDelay(basichttpparams, true);
    HttpConnectionParams.setSocketBufferSize(basichttpparams, 8192);
    HttpProtocolParams.setVersion(basichttpparams, HttpVersion.HTTP_1_1);
    ThreadSafeClientConnManager threadsafeclientconnmanager = new ThreadSafeClientConnManager(basichttpparams, schemeregistry);
    e = getDefaultThreadPool();
    f = new WeakHashMap();
    g = new HashMap();
    d = new SyncBasicHttpContext(new BasicHttpContext());
    c = new DefaultHttpClient(threadsafeclientconnmanager, basichttpparams);
    c.addRequestInterceptor(new a(this));
    c.addResponseInterceptor(new b(this));
    c.addRequestInterceptor(new c(this), 0);
    c.setHttpRequestRetryHandler(new z(5, 1500));
}
 
Example 7
Source File: HttpAndroidClientFactory.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
public HttpClient createHttpClient(ClientConfiguration clientconfiguration)
{
    BasicHttpParams basichttpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(basichttpparams, clientconfiguration.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(basichttpparams, clientconfiguration.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(basichttpparams, true);
    HttpConnectionParams.setTcpNoDelay(basichttpparams, true);
    int i = clientconfiguration.getSocketBufferSizeHints()[0];
    int j = clientconfiguration.getSocketBufferSizeHints()[1];
    if (i > 0 || j > 0)
    {
        HttpConnectionParams.setSocketBufferSize(basichttpparams, Math.max(i, j));
    }
    SchemeRegistry schemeregistry = new SchemeRegistry();
    schemeregistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (clientconfiguration.getProtocol() == Protocol.HTTPS)
    {
        schemeregistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    }
    return new DefaultHttpClient(new SingleClientConnManager(basichttpparams, schemeregistry), basichttpparams);
}
 
Example 8
Source File: HttpClientFactory.java    From miappstore with Apache License 2.0 6 votes vote down vote up
private static HttpParams createHttpParams() {
	final HttpParams params = new BasicHttpParams();
	// 设置是否启用旧连接检查,默认是开启的。关闭这个旧连接检查可以提高一点点性能,但是增加了I/O错误的风险(当服务端关闭连接时)。
	// 开启这个选项则在每次使用老的连接之前都会检查连接是否可用,这个耗时大概在15-30ms之间
	HttpConnectionParams.setStaleCheckingEnabled(params, false);
	HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);// 设置链接超时时间
	HttpConnectionParams.setSoTimeout(params, TIMEOUT);// 设置socket超时时间
	HttpConnectionParams.setSocketBufferSize(params, SOCKET_BUFFER_SIZE);// 设置缓存大小
	HttpConnectionParams.setTcpNoDelay(params, true);// 是否不使用延迟发送(true为不延迟)
	HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // 设置协议版本
	HttpProtocolParams.setUseExpectContinue(params, true);// 设置异常处理机制
	HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);// 设置编码
	HttpClientParams.setRedirecting(params, false);// 设置是否采用重定向

	ConnManagerParams.setTimeout(params, TIMEOUT);// 设置超时
	ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(MAX_CONNECTIONS));// 多线程最大连接数
	ConnManagerParams.setMaxTotalConnections(params, 10); // 多线程总连接数
	return params;
}
 
Example 9
Source File: NetworkHelper.java    From fanfouapp-opensource with Apache License 2.0 6 votes vote down vote up
private static final HttpParams createHttpParams() {
    final HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    ConnManagerParams.setTimeout(params, NetworkHelper.SOCKET_TIMEOUT_MS);
    HttpConnectionParams.setConnectionTimeout(params,
            NetworkHelper.CONNECTION_TIMEOUT_MS);
    HttpConnectionParams.setSoTimeout(params,
            NetworkHelper.SOCKET_TIMEOUT_MS);

    ConnManagerParams.setMaxConnectionsPerRoute(params,
            new ConnPerRouteBean(NetworkHelper.MAX_TOTAL_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(params,
            NetworkHelper.MAX_TOTAL_CONNECTIONS);

    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params,
            NetworkHelper.SOCKET_BUFFER_SIZE);
    HttpClientParams.setRedirecting(params, false);
    HttpProtocolParams.setUserAgent(params, "FanFou for Android/"
            + AppContext.appVersionName);
    return params;
}
 
Example 10
Source File: ApacheClient.java    From android-lite-http with Apache License 2.0 5 votes vote down vote up
/**
 * initialize HttpParams , initialize settings such as total connextions,timeout ...
 */
private BasicHttpParams createHttpParams() {
    BasicHttpParams params = new BasicHttpParams();
    ConnManagerParams.setTimeout(params, DEFAULT_TIMEOUT);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(DEFAULT_MAX_CONN_PER_ROUT));
    ConnManagerParams.setMaxTotalConnections(params, DEFAULT_MAX_CONN_TOTAL);
    HttpConnectionParams.setTcpNoDelay(params, TCP_NO_DELAY);
    HttpConnectionParams.setConnectionTimeout(params, DEFAULT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, DEFAULT_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, DEFAULT_BUFFER_SIZE);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, userAgent);
    // settingOthers(params);
    return params;
}
 
Example 11
Source File: RestProtocol.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
        if (connectionMonitor == null) {
            connectionMonitor = new ConnectionMonitor();
        }

        // TODO more configs to add

        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
        // 20 is the default maxTotal of current PoolingClientConnectionManager
        connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
        connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

        connectionMonitor.addConnectionManager(connectionManager);

//        BasicHttpContext localContext = new BasicHttpContext();

        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        return Long.parseLong(value) * 1000;
                    }
                }
                // TODO constant
                return 30 * 1000;
            }
        });

        HttpParams params = httpClient.getParams();
        // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
        HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoKeepalive(params, true);

        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

        ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
        clients.add(client);

        client.register(RpcContextFilter.class);
        for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
            if (!StringUtils.isEmpty(clazz)) {
                try {
                    client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
                } catch (ClassNotFoundException e) {
                    throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
                }
            }
        }

        // TODO protocol
        ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
        return target.proxy(serviceType);
    }
 
Example 12
Source File: RestProtocol.java    From dubbox-hystrix with Apache License 2.0 4 votes vote down vote up
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
        if (connectionMonitor == null) {
            connectionMonitor = new ConnectionMonitor();
        }

        // TODO more configs to add

        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
        // 20 is the default maxTotal of current PoolingClientConnectionManager
        connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
        connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

        connectionMonitor.addConnectionManager(connectionManager);

//        BasicHttpContext localContext = new BasicHttpContext();

        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        return Long.parseLong(value) * 1000;
                    }
                }
                // TODO constant
                return 30 * 1000;
            }
        });

        HttpParams params = httpClient.getParams();
        // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
        HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoKeepalive(params, true);

        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

        ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
        clients.add(client);

        client.register(RpcContextFilter.class);
        for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
            if (!StringUtils.isEmpty(clazz)) {
                try {
                    client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
                } catch (ClassNotFoundException e) {
                    throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
                }
            }
        }

        // TODO protocol
        ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
        return target.proxy(serviceType);
    }
 
Example 13
Source File: RestProtocol.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
        if (connectionMonitor == null) {
            connectionMonitor = new ConnectionMonitor();
        }

        // TODO more configs to add

        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
        // 20 is the default maxTotal of current PoolingClientConnectionManager
        connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
        connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

        connectionMonitor.addConnectionManager(connectionManager);

//        BasicHttpContext localContext = new BasicHttpContext();

        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        return Long.parseLong(value) * 1000;
                    }
                }
                // TODO constant
                return 30 * 1000;
            }
        });

        HttpParams params = httpClient.getParams();
        // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
        HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoKeepalive(params, true);

        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

        ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
        clients.add(client);

        client.register(RpcContextFilter.class);
        for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
            if (!StringUtils.isEmpty(clazz)) {
                try {
                    client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
                } catch (ClassNotFoundException e) {
                    throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
                }
            }
        }

        // TODO protocol
        ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
        return target.proxy(serviceType);
    }
 
Example 14
Source File: RestProtocol.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
        if (connectionMonitor == null) {
            connectionMonitor = new ConnectionMonitor();
        }

        // TODO more configs to add

        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
        // 20 is the default maxTotal of current PoolingClientConnectionManager
        connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
        connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

        connectionMonitor.addConnectionManager(connectionManager);

//        BasicHttpContext localContext = new BasicHttpContext();

        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        return Long.parseLong(value) * 1000;
                    }
                }
                // TODO constant
                return 30 * 1000;
            }
        });

        HttpParams params = httpClient.getParams();
        // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
        HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoKeepalive(params, true);

        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

        ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
        clients.add(client);

        client.register(RpcContextFilter.class);
        for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
            if (!StringUtils.isEmpty(clazz)) {
                try {
                    client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
                } catch (ClassNotFoundException e) {
                    throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
                }
            }
        }

        // TODO protocol
        ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
        return target.proxy(serviceType);
    }
 
Example 15
Source File: MwsConnection.java    From amazon-mws-orders with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize the connection.
 */
synchronized void freeze() {
    if (frozen) {
        return;
    }
    if (userAgent == null) {
        setDefaultUserAgent();
    }
    serviceMap = new HashMap<String, ServiceEndpoint>();
    if (log.isDebugEnabled()) {
        StringBuilder buf = new StringBuilder();
        buf.append("Creating MwsConnection {");
        buf.append("applicationName:");
        buf.append(applicationName);
        buf.append(",applicationVersion:");
        buf.append(applicationVersion);
        buf.append(",awsAccessKeyId:");
        buf.append(awsAccessKeyId);
        buf.append(",uri:");
        buf.append(endpoint.toString());
        buf.append(",userAgent:");
        buf.append(userAgent);
        buf.append(",connectionTimeout:");
        buf.append(connectionTimeout);
        if (proxyHost != null && proxyPort != 0) {
            buf.append(",proxyUsername:");
            buf.append(proxyUsername);
            buf.append(",proxyHost:");
            buf.append(proxyHost);
            buf.append(",proxyPort:");
            buf.append(proxyPort);
        }
        buf.append("}");
        log.debug(buf);
    }

    BasicHttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(CoreProtocolPNames.USER_AGENT, userAgent);
    HttpConnectionParams
            .setConnectionTimeout(httpParams, connectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, true);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);

    connectionManager = getConnectionManager();
    httpClient = new DefaultHttpClient(connectionManager, httpParams);
    httpContext = new BasicHttpContext();
    if (proxyHost != null && proxyPort != 0) {
        String scheme = MwsUtl.usesHttps(endpoint) ? "https" : "http";
        HttpHost hostConfiguration = new HttpHost(proxyHost, proxyPort, scheme);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, hostConfiguration);

        if (proxyUsername != null && proxyPassword != null) {
            Credentials credentials = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
            CredentialsProvider cprovider = new BasicCredentialsProvider();
            cprovider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials);
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, cprovider);
        }
    }
    headers = Collections.unmodifiableMap(headers);
    frozen = true;
}