Java Code Examples for org.apache.http.params.BasicHttpParams

The following examples show how to use org.apache.http.params.BasicHttpParams. These examples are extracted from open source projects. 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 Project: fanfouapp-opensource   Source File: NetworkHelper.java    License: 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 2
Source Project: iaf   Source File: WebServiceNtlmSender.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws ConfigurationException {
	super.configure();

	HttpParams httpParameters = new BasicHttpParams();
	HttpConnectionParams.setConnectionTimeout(httpParameters, getTimeout());
	HttpConnectionParams.setSoTimeout(httpParameters, getTimeout());
	httpClient = new DefaultHttpClient(connectionManager, httpParameters);
	httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory());
	CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
	httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new NTCredentials(cf.getUsername(), cf.getPassword(), Misc.getHostname(), getAuthDomain()));
	if (StringUtils.isNotEmpty(getProxyHost())) {
		HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
	}
}
 
Example 3
Source Project: kylin-on-parquet-v2   Source File: RestClient.java    License: Apache License 2.0 6 votes vote down vote up
private void init(String host, int port, String userName, String password) {
    this.host = host;
    this.port = port;
    this.userName = userName;
    this.password = password;
    this.baseUrl = SCHEME_HTTP + host + ":" + port + KYLIN_API_PATH;

    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setSoTimeout(httpParams, httpSocketTimeoutMs);
    HttpConnectionParams.setConnectionTimeout(httpParams, httpConnectionTimeoutMs);

    final PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    KylinConfig config = KylinConfig.getInstanceFromEnv();
    cm.setDefaultMaxPerRoute(config.getRestClientDefaultMaxPerRoute());
    cm.setMaxTotal(config.getRestClientMaxTotal());

    client = new DefaultHttpClient(cm, httpParams);

    if (userName != null && password != null) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        client.setCredentialsProvider(provider);
    }
}
 
Example 4
Source Project: android-advanced-light   Source File: MainActivity.java    License: 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 5
Source Project: letv   Source File: PoolingClientConnectionManager.java    License: 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 6
Source Project: Huochexing12306   Source File: MyHtttpClient.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized static DefaultHttpClient getHttpClient() {
	try {
		HttpParams params = new BasicHttpParams();
		// 设置一些基本参数
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		// 超时设置
		// 从连接池中取连接的超时时间
		ConnManagerParams.setTimeout(params, 10000); // 连接超时
		HttpConnectionParams.setConnectionTimeout(params, 10000); // 请求超时
		HttpConnectionParams.setSoTimeout(params, 30000);
		SchemeRegistry registry = new SchemeRegistry();
		Scheme sch1 = new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80);
		registry.register(sch1);
		// 使用线程安全的连接管理来创建HttpClient
		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
				params, registry);
		mHttpClient = new DefaultHttpClient(conMgr, params);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return mHttpClient;
}
 
Example 7
Source Project: AppServiceRestFul   Source File: Util.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static HttpClient getNewHttpClient() { 
   try { 
       KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
       trustStore.load(null, null); 

       SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); 
       sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

       HttpParams params = new BasicHttpParams(); 
       HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
       HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

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

       ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); 

       return new DefaultHttpClient(ccm, params); 
   } catch (Exception e) { 
       return new DefaultHttpClient(); 
   } 
}
 
Example 8
Source Project: AppServiceRestFul   Source File: Util.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static HttpClient getNewHttpClient() { 
   try { 
       KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
       trustStore.load(null, null); 

       SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); 
       sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

       HttpParams params = new BasicHttpParams(); 
       HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
       HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

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

       ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); 

       return new DefaultHttpClient(ccm, params); 
   } catch (Exception e) { 
       return new DefaultHttpClient(); 
   } 
}
 
Example 9
/**
 * prepare for the https connection
 * call this in the constructor of the class that does the connection if
 * it's used multiple times
 */
private void setup() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    // http scheme
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // https scheme
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

    params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
    params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf8");

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // set the user credentials for our site "example.com"
    credentialsProvider.setCredentials(new AuthScope("example.com", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("UserNameHere", "UserPasswordHere"));
    clientConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);

    context = new BasicHttpContext();
    context.setAttribute("http.auth.credentials-provider", credentialsProvider);
}
 
Example 10
public InputStream getStream(String url) {
    HttpParams httpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams,
            CONNECTION_TIMEOUT);
    HttpClient client = new DefaultHttpClient(httpparams);
    HttpGet get = new HttpGet(url);

    try {
        HttpResponse response = client.execute(get);
        int status = response.getStatusLine().getStatusCode();

        if (200 == status) {
            return response.getEntity().getContent();
        }
    } catch (Exception e) {
        Log.i(TAG, e.getMessage());
    }

    return null;
}
 
Example 11
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 12
Source Project: android-project-wo2b   Source File: MySSLSocketFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore
 *
 * @param keyStore custom provided KeyStore instance
 * @return DefaultHttpClient
 */
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {

    try {
        SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}
 
Example 13
public static void loginBayFiles() throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setParameter(
            "http.useragent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
    DefaultHttpClient httpclient = new DefaultHttpClient(params);

    System.out.println("Trying to log in to bayfiles.com");

    HttpPost httppost = new HttpPost("http://api.bayfiles.com/v1/account/login/007007dinesh/passwordhere");

    HttpResponse httpresponse = httpclient.execute(httppost);

    String loginResponse = EntityUtils.toString(httpresponse.getEntity());
    if (loginResponse.contains("session")) {
        login = true;
        sessioncookie = parseResponse(loginResponse, "\"session\":\"", "\"");
        System.out.println("Session : "+sessioncookie);
        System.out.println("Bayfiles.com login succeeded :)");
    } else {
        login = false;
        System.out.println("BayFiles.com Login failed :(");
    }

}
 
Example 14
Source Project: onboard   Source File: ApiProxyServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init() throws ServletException {
    String doLogStr = getConfigParam(P_LOG);
    if (doLogStr != null) {
        this.doLog = Boolean.parseBoolean(doLogStr);
    }

    String doForwardIPString = getConfigParam(P_FORWARDEDFOR);
    if (doForwardIPString != null) {
        this.doForwardIP = Boolean.parseBoolean(doForwardIPString);
    }

    initTarget();// sets target*

    HttpParams hcParams = new BasicHttpParams();
    hcParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    readConfigParam(hcParams, ClientPNames.HANDLE_REDIRECTS, Boolean.class);
    proxyClient = createHttpClient(hcParams);
}
 
Example 15
Source Project: Android-Basics-Codes   Source File: MySSLSocketFactory.java    License: Artistic License 2.0 6 votes vote down vote up
/**
 * Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore
 *
 * @param keyStore custom provided KeyStore instance
 * @return DefaultHttpClient
 */
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {

    try {
        SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}
 
Example 16
Source Project: Onosendai   Source File: HttpClientFactory.java    License: 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 17
Source Project: MiBandDecompiled   Source File: AsyncHttpClient.java    License: 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 18
Source Project: BotLibre   Source File: Utils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static String httpAuthPOST(String url, String user, String password, Map<String, String> formParams) throws Exception {
	HttpPost request = new HttpPost(url);
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
	List<NameValuePair> params = new ArrayList<NameValuePair>();
	for (Map.Entry<String, String> entry : formParams.entrySet()) {
		params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
	}
	request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
	HttpParams httpParams = new BasicHttpParams();
	HttpConnectionParams.setConnectionTimeout(httpParams, URL_TIMEOUT);
	HttpConnectionParams.setSoTimeout(httpParams, URL_TIMEOUT);
	DefaultHttpClient client = new DefaultHttpClient(httpParams);
	client.getCredentialsProvider().setCredentials(
			new AuthScope(AuthScope.ANY),
			new UsernamePasswordCredentials(user, password));
	HttpResponse response = client.execute(request);
	return fetchResponse(response);
}
 
Example 19
Source Project: kylin   Source File: RestClient.java    License: Apache License 2.0 6 votes vote down vote up
private void init(String host, int port, String userName, String password) {
    this.host = host;
    this.port = port;
    this.userName = userName;
    this.password = password;
    this.baseUrl = SCHEME_HTTP + host + ":" + port + KYLIN_API_PATH;

    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setSoTimeout(httpParams, httpSocketTimeoutMs);
    HttpConnectionParams.setConnectionTimeout(httpParams, httpConnectionTimeoutMs);

    final PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    KylinConfig config = KylinConfig.getInstanceFromEnv();
    cm.setDefaultMaxPerRoute(config.getRestClientDefaultMaxPerRoute());
    cm.setMaxTotal(config.getRestClientMaxTotal());

    client = new DefaultHttpClient(cm, httpParams);

    if (userName != null && password != null) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        client.setCredentialsProvider(provider);
    }
}
 
Example 20
Source Project: miappstore   Source File: HttpClientFactory.java    License: 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 21
Source Project: neembuu-uploader   Source File: CheckUser.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void getCanCustomizeNormalizing(UserSetPriv usp) {
    boolean canCustomizeNormalizing = true;
    String normalization = ".neembuu";
    HttpParams params = new BasicHttpParams();
    params.setParameter(
            "http.useragent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
    HttpClient httpclient = NUHttpClient.getHttpClient();
    HttpGet httpget = new HttpGet("http://neembuu.com/uploader/api/user.xml?userid="+UserImpl.I().uid());
    NULogger.getLogger().info("Checking for user priviledges ...");
    try {
        HttpResponse response = httpclient.execute(httpget);
        String respxml = EntityUtils.toString(response.getEntity());
        canCustomizeNormalizing = getCanCustomizeNormalizingFromXml(respxml);
        normalization = getNormalization(respxml);
        NULogger.getLogger().log(Level.INFO, "CanCustomizeNormalizing: {0}", canCustomizeNormalizing);
    } catch (Exception ex) {
        NULogger.getLogger().log(Level.INFO, "Exception while checking update\n{0}", ex);
    }
    usp.setCanCustomizeNormalizing(canCustomizeNormalizing);
    usp.setNormalization(normalization);
}
 
Example 22
Source Project: galaxy-sdk-java   Source File: MetricsClientFactory.java    License: Apache License 2.0 6 votes vote down vote up
public static HttpClient generateHttpClient(final int maxTotalConnections,
    final int maxTotalConnectionsPerRoute, int connTimeout) {
  HttpParams params = new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params, maxTotalConnections);
  ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() {
    @Override
    public int getMaxForRoute(HttpRoute route) {
      return maxTotalConnectionsPerRoute;
    }
  });
  HttpConnectionParams
      .setConnectionTimeout(params, connTimeout);
  SchemeRegistry schemeRegistry = new SchemeRegistry();
  schemeRegistry.register(
      new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
  sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
  ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schemeRegistry);
  return new DefaultHttpClient(conMgr, params);
}
 
Example 23
Source Project: kylin-on-parquet-v2   Source File: RestService.java    License: Apache License 2.0 5 votes vote down vote up
private HttpClient getHttpClient(int connectionTimeout, int readTimeout) {
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setSoTimeout(httpParams, readTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout);

    return new DefaultHttpClient(httpParams);
}
 
Example 24
/**
 * Replicates default connection and protocol parameters used within
 * {@link ApacheHttpTransport#newDefaultHttpClient()} with one exception:
 *
 * Stale checking is enabled.
 */
HttpParams newDefaultHttpParams() {
  HttpParams params = new BasicHttpParams();
  HttpConnectionParams.setStaleCheckingEnabled(params, true);
  HttpConnectionParams.setSocketBufferSize(params, 8192);
  ConnManagerParams.setMaxTotalConnections(params, 200);
  ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(200));
  return params;
}
 
Example 25
protected void initClient(DatabricksServiceFactory.Builder builder) {
  try {

    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(null, null, new SecureRandom());

    SSLSocketFactory sf = new SSLSocketFactory(sslContext);
    Scheme httpsScheme = new Scheme("https", HTTPS_PORT, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, builder.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(params, builder.getSoTimeout());

    DefaultHttpClient defaultHttpClient = new DefaultHttpClient(cm, params);
    defaultHttpClient.setHttpRequestRetryHandler(retryHandler);

    // set authorization header if token base
    if (isNotEmpty(builder.getToken())) {
      isTokenAuth = true;
      authToken = builder.getToken();

    } else if (isNotEmpty(builder.getUsername()) && isNotEmpty(builder.getPassword())) {
      defaultHttpClient.getCredentialsProvider().setCredentials(
          new AuthScope(host, HTTPS_PORT),
          new UsernamePasswordCredentials(builder.getUsername(), builder.getPassword()));
    }

    client = new AutoRetryHttpClient(defaultHttpClient, retryStrategy);

  } catch (Exception e) {
    logger.error("", e);
  }

  url = String.format("https://%s/api/%s", host, apiVersion);
  mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
}
 
Example 26
/**
 * 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 27
/**
 * UserAgentRequestHeader adds correct header with current version.
 * @throws Exception If something goes wrong.
 */
@Test
public void correctUserAgentHeader() throws Exception {
    final RequestLine mockRequestLine = Mockito.mock(RequestLine.class);
    Mockito.when(mockRequestLine.getMethod()).thenReturn("GET");
    final HttpRequest mockRequest = Mockito.mock(HttpRequest.class);
    Mockito.when(mockRequest.getRequestLine()).thenReturn(mockRequestLine);
    Mockito.when(mockRequest.getParams()).thenReturn(new BasicHttpParams());

    final UserAgentRequestHeader header = new UserAgentRequestHeader();
    header.process(mockRequest, null);

    final ArgumentCaptor<Header> headerCaptor =
        ArgumentCaptor.forClass(Header.class);
    Mockito.verify(mockRequest).addHeader(headerCaptor.capture());
    MatcherAssert.assertThat(
        "Header name must be User-Agent",
        headerCaptor.getValue().getName(),
        new IsEqual<>("User-Agent")
    );
    final Pattern pattern =
        Pattern.compile("(?<=docker-java-api.\\/.)(.*)(?=.See)");
    final Matcher matcher =
        pattern.matcher(headerCaptor.getValue().getValue());
    MatcherAssert.assertThat(
        "Header value must have version in it",
        matcher.find(),
        new IsEqual<>(true)
    );
}
 
Example 28
/**
 * @deprecated version.xml is located in update.zip which is used to get list 
 * of latest plugins
 */
@Deprecated 
private static String getVersionXmlOnline()throws IOException{
    HttpParams params = new BasicHttpParams();
    params.setParameter(
            "http.useragent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
    DefaultHttpClient httpclient = new DefaultHttpClient(params);
    HttpGet httpget = new HttpGet("http://neembuuuploader.sourceforge.net/version.xml");
    NULogger.getLogger().info("Checking for new version...");
    HttpResponse response = httpclient.execute(httpget);
    return EntityUtils.toString(response.getEntity());
}
 
Example 29
public static HttpParams getTimeoutHttpParams() {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);

    return params;
}
 
Example 30
Source Project: io   Source File: HttpClientFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * HTTPClientオブジェクトを作成.
 * @param type 通信タイプ
 * @param connectionTimeout タイムアウト値(ミリ秒)。0の場合はデフォルト値を利用する。
 * @return 作成したHttpClientクラスインスタンス
 */
public static HttpClient create(final String type, final int connectionTimeout) {
    if (TYPE_DEFAULT.equalsIgnoreCase(type)) {
        return new DefaultHttpClient();
    }

    SSLSocketFactory sf = null;
    try {
        if (TYPE_INSECURE.equalsIgnoreCase(type)) {
            sf = createInsecureSSLSocketFactory();
        }
    } catch (Exception e) {
        return null;
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", PORTHTTPS, sf));
    schemeRegistry.register(new Scheme("http", PORTHTTP, PlainSocketFactory.getSocketFactory()));
    HttpParams params = new BasicHttpParams();
    ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
    // ClientConnectionManager cm = new
    // ThreadSafeClientConnManager(schemeRegistry);
    HttpClient hc = new DefaultHttpClient(cm, params);

    HttpParams params2 = hc.getParams();
    int timeout = TIMEOUT;
    if (connectionTimeout != 0) {
        timeout = connectionTimeout;
    }
    HttpConnectionParams.setConnectionTimeout(params2, timeout); // 接続のタイムアウト
    HttpConnectionParams.setSoTimeout(params2, timeout); // データ取得のタイムアウト
    return hc;
}