org.apache.http.client.params.HttpClientParams Java Examples

The following examples show how to use org.apache.http.client.params.HttpClientParams. 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: 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 #2
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 #3
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 #4
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 #5
Source File: HttpClientFactory.java    From Onosendai with Apache License 2.0 6 votes vote down vote up
private HttpClient makeHttpClient () throws IOException, GeneralSecurityException {
	final HttpParams params = new BasicHttpParams();
	HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
	HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
	HttpConnectionParams.setSocketBufferSize(params, SO_BUFFER_SIZE);
	HttpClientParams.setRedirecting(params, false);

	final ClientConnectionManager conman = new ThreadSafeClientConnManager(params, new SchemeRegistry());

	if (this.tsPath != null) {
		addHttpsSchemaForTrustStore(conman, this.tsPath, this.tsPassword);
	}
	else {
		addHttpsSchema(conman);
	}

	return new DefaultHttpClient(conman, params);
}
 
Example #6
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 #7
Source File: Http4Util.java    From httpsig-java with The Unlicense 6 votes vote down vote up
public static void enableAuth(final AbstractHttpClient client, final Keychain keychain, final KeyId keyId) {
    if (client == null) {
        throw new NullPointerException("client");
    }

    if (keychain == null) {
        throw new NullPointerException("keychain");
    }

    client.getAuthSchemes().register(Constants.SCHEME, new AuthSchemeFactory() {
        public AuthScheme newInstance(HttpParams params) {
            return new Http4SignatureAuthScheme();
        }
    });

    Signer signer = new Signer(keychain, keyId);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, new SignerCredentials(signer));
    client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF,
                                    Arrays.asList(Constants.SCHEME));

    HttpClientParams.setAuthenticating(client.getParams(), true);
}
 
Example #8
Source File: AndroidHttpClient.java    From android-download-manager with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * 
 * @param userAgent
 *            to report in your HTTP requests
 * @param context
 *            to use for caching SSL sessions (may be null for no caching)
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent,
		Context context) {
	HttpParams params = new BasicHttpParams();

	// Turn off stale checking. Our connections break all the time anyway,
	// and it's not worth it to pay the penalty of checking every time.
	HttpConnectionParams.setStaleCheckingEnabled(params, false);

	HttpConnectionParams.setConnectionTimeout(params,
			SOCKET_OPERATION_TIMEOUT);
	HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
	HttpConnectionParams.setSocketBufferSize(params, 8192);

	// Don't handle redirects -- return them to the caller. Our code
	// often wants to re-POST after a redirect, which we must do ourselves.
	HttpClientParams.setRedirecting(params, false);

	// Use a session cache for SSL sockets
	// SSLSessionCache sessionCache = context == null ? null : new
	// SSLSessionCache(context);

	// Set the specified user agent and register standard protocols.
	HttpProtocolParams.setUserAgent(params, userAgent);
	SchemeRegistry schemeRegistry = new SchemeRegistry();
	schemeRegistry.register(new Scheme("http", PlainSocketFactory
			.getSocketFactory(), 80));
	// schemeRegistry.register(new Scheme("https",
	// SSLCertificateSocketFactory.getHttpSocketFactory(
	// SOCKET_OPERATION_TIMEOUT, sessionCache), 443));

	ClientConnectionManager manager = new ThreadSafeClientConnManager(
			params, schemeRegistry);

	// We use a factory method to modify superclass initialization
	// parameters without the funny call-a-static-method dance.
	return new AndroidHttpClient(manager, params);
}
 
Example #9
Source File: NFHttpClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
void init(IClientConfig config, boolean registerMonitor) {
	HttpParams params = getParams();

	HttpProtocolParams.setContentCharset(params, "UTF-8");  
	params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, 
			ThreadSafeClientConnManager.class.getName());
	HttpClientParams.setRedirecting(params, config.get(CommonClientConfigKey.FollowRedirects, true));
	// set up default headers
	List<Header> defaultHeaders = new ArrayList<Header>();
	defaultHeaders.add(new BasicHeader("Netflix.NFHttpClient.Version", "1.0"));
	defaultHeaders.add(new BasicHeader("X-netflix-httpclientname", name));
	params.setParameter(ClientPNames.DEFAULT_HEADERS, defaultHeaders);

	connPoolCleaner = new ConnectionPoolCleaner(name, this.getConnectionManager(), connectionPoolCleanUpScheduler);

	this.retriesProperty = config.getGlobalProperty(RETRIES.format(name));

	this.sleepTimeFactorMsProperty = config.getGlobalProperty(SLEEP_TIME_FACTOR_MS.format(name));
	setHttpRequestRetryHandler(
			new NFHttpMethodRetryHandler(this.name, this.retriesProperty.getOrDefault(), false,
					this.sleepTimeFactorMsProperty.getOrDefault()));
    tracer = Monitors.newTimer(EXECUTE_TRACER + "-" + name, TimeUnit.MILLISECONDS);
    if (registerMonitor) {
           Monitors.registerObject(name, this);
    }
    maxTotalConnectionProperty = config.getDynamicProperty(CommonClientConfigKey.MaxTotalHttpConnections);
    maxTotalConnectionProperty.onChange(newValue ->
    	((ThreadSafeClientConnManager) getConnectionManager()).setMaxTotal(newValue)
    );

    maxConnectionPerHostProperty = config.getDynamicProperty(CommonClientConfigKey.MaxHttpConnectionsPerHost);
    maxConnectionPerHostProperty.onChange(newValue ->
		((ThreadSafeClientConnManager) getConnectionManager()).setDefaultMaxPerRoute(newValue)
       );

	connIdleEvictTimeMilliSeconds = config.getGlobalProperty(CONN_IDLE_EVICT_TIME_MILLIS.format(name));
}
 
Example #10
Source File: ConfigurationService.java    From RoboZombie with Apache License 2.0 5 votes vote down vote up
/**
 * <p>The <i>out-of-the-box</i> configuration for an instance of {@link HttpClient} which will be used for 
 * executing all endpoint requests. Below is a detailed description of all configured properties.</p> 
 * <br>
 * <ul>
 * <li>
 * <p><b>HttpClient</b></p>
 * <br>
 * <p>It registers two {@link Scheme}s:</p>
 * <br>
 * <ol>
 * 	<li><b>HTTP</b> on port <b>80</b> using sockets from {@link PlainSocketFactory#getSocketFactory}</li>
 * 	<li><b>HTTPS</b> on port <b>443</b> using sockets from {@link SSLSocketFactory#getSocketFactory}</li>
 * </ol>
 * 
 * <p>It uses a {@link ThreadSafeClientConnManager} with the following parameters:</p>
 * <br>
 * <ol>
 * 	<li><b>Redirecting:</b> enabled</li>
 * 	<li><b>Connection Timeout:</b> 30 seconds</li>
 * 	<li><b>Socket Timeout:</b> 30 seconds</li>
 * 	<li><b>Socket Buffer Size:</b> 12000 bytes</li>
 * 	<li><b>User-Agent:</b> via <code>System.getProperty("http.agent")</code></li>
 * </ol>
 * </li>
 * </ul>
 * @return the instance of {@link HttpClient} which will be used for request execution
 * <br><br>
 * @since 1.3.0
 */
@Override
public Configuration getDefault() {
	
	return new Configuration() {

		@Override
		public HttpClient httpClient() {
			
			try {
			
				HttpParams params = new BasicHttpParams();
				HttpClientParams.setRedirecting(params, true);
				HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
				HttpConnectionParams.setSoTimeout(params, 30 * 1000);
				HttpConnectionParams.setSocketBufferSize(params, 12000);
		        HttpProtocolParams.setUserAgent(params, System.getProperty("http.agent"));
		        
		        SchemeRegistry schemeRegistry = new SchemeRegistry();
		        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

		        ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

		        return new DefaultHttpClient(manager, params);
			}
			catch(Exception e) {
				
				throw new ConfigurationFailedException(e);
			}
		}
	};
}
 
Example #11
Source File: ExampleSocialActivity.java    From android-profile with Apache License 2.0 4 votes vote down vote up
private Bitmap downloadBitmapWithClient(String url) {
    final AndroidHttpClient httpClient = AndroidHttpClient.newInstance("Android");
    HttpClientParams.setRedirecting(httpClient.getParams(), true);
    final HttpGet request = new HttpGet(url);

    try {
        HttpResponse response = httpClient.execute(request);
        final int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            Header[] headers = response.getHeaders("Location");

            if (headers != null && headers.length != 0) {
                String newUrl = headers[headers.length - 1].getValue();
                // call again with new URL
                return downloadBitmap(newUrl);
            } else {
                return null;
            }
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();

                // do your work here
                return BitmapFactory.decodeStream(inputStream);
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (Exception e) {
        request.abort();
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }

    return null;
}
 
Example #12
Source File: DcRestAdapter.java    From io with Apache License 2.0 4 votes vote down vote up
/**
 * コンストラクタ.
 */
public DcRestAdapter() {
    httpClient = HttpClientFactory.create("insecure", TIMEOUT);
    HttpClientParams.setRedirecting(httpClient.getParams(), false);
    log = LogFactory.getLog(DcRestAdapter.class);
}
 
Example #13
Source File: Utilities.java    From TurkcellUpdater_android_sdk with Apache License 2.0 4 votes vote down vote up
static DefaultHttpClient createClient(String userAgent,
		boolean acceptAllSslCertificates) {

	HttpParams params = new BasicHttpParams();
	HttpConnectionParams.setStaleCheckingEnabled(params, false);
	HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);

	// to make connection pool more fault tolerant
	ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() {
		public int getMaxForRoute(HttpRoute route) {
			return 10;
		}
	});

	HttpConnectionParams.setSoTimeout(params, 20 * 1000);

	HttpConnectionParams.setSocketBufferSize(params, 8192);

	HttpClientParams.setRedirecting(params, false);

	HttpProtocolParams.setUserAgent(params, userAgent);

	SSLSocketFactory sslSocketFactory = null;

	if (acceptAllSslCertificates) {
		try {
			sslSocketFactory = new AcceptAllSocketFactory();
		} catch (Exception e) {
			// omitted
		}
	}

	if (sslSocketFactory == null) {
		sslSocketFactory = SSLSocketFactory.getSocketFactory();
	}

	SchemeRegistry schemeRegistry = new SchemeRegistry();
	schemeRegistry.register(new Scheme("http", PlainSocketFactory
			.getSocketFactory(), 80));
	schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));

	ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(
			params, schemeRegistry);

	final DefaultHttpClient client = new DefaultHttpClient(manager, params);

	return client;
}