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); }
public static b a(String str) { HttpParams basicHttpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(basicHttpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUseExpectContinue(basicHttpParams, false); HttpConnectionParams.setStaleCheckingEnabled(basicHttpParams, false); HttpConnectionParams.setConnectionTimeout(basicHttpParams, 20000); HttpConnectionParams.setSoTimeout(basicHttpParams, 30000); HttpConnectionParams.setSocketBufferSize(basicHttpParams, 8192); HttpClientParams.setRedirecting(basicHttpParams, true); HttpClientParams.setAuthenticating(basicHttpParams, false); HttpProtocolParams.setUserAgent(basicHttpParams, str); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme(com.alipay.sdk.cons.b.a, SSLCertificateSocketFactory.getHttpSocketFactory(30000, null), WebSocket.DEFAULT_WSS_PORT)); ClientConnectionManager threadSafeClientConnManager = new ThreadSafeClientConnManager(basicHttpParams, schemeRegistry); ConnManagerParams.setTimeout(basicHttpParams, 60000); ConnManagerParams.setMaxConnectionsPerRoute(basicHttpParams, new ConnPerRouteBean(10)); ConnManagerParams.setMaxTotalConnections(basicHttpParams, 50); Security.setProperty("networkaddress.cache.ttl", "-1"); HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); return new b(threadSafeClientConnManager, basicHttpParams); }
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; }
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; }
/** * Create a thread-safe client. This client does not do redirecting, to allow us to capture * correct "error" codes. * * @return HttpClient */ public static final DefaultHttpClient createHttpClient() { // Sets up the http part of the service. final SchemeRegistry supportedSchemes = new SchemeRegistry(); // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. final SocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", sf, 80)); supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // Set some client http client parameter defaults. final HttpParams httpParams = createHttpParams(); HttpClientParams.setRedirecting(httpParams, false); final ClientConnectionManager ccm = new ThreadSafeClientConnManager(httpParams, supportedSchemes); return new DefaultHttpClient(ccm, httpParams); }
/** * Do a http get for the given url. * * @param url requested url * @param parameters request parameters * @param accessor oauth accessor * @return the http response * @throws IOException * @throws {@link YNoteException} */ public static HttpResponse doGet(String url, Map<String, String> parameters, OAuthAccessor accessor) throws IOException, YNoteException { // add ynote parameters to the url OAuth.addParameters(url, parameters == null ? null : parameters.entrySet()); HttpGet get = new HttpGet(url); // sign all parameters, including oauth parameters and ynote parameters // and add the oauth related information into the header Header oauthHeader = getAuthorizationHeader(url, OAuthMessage.GET, parameters, accessor); get.addHeader(oauthHeader); HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); get.setParams(params); HttpResponse response = client.execute(get); if ((response.getStatusLine().getStatusCode() / 100) != 2) { YNoteException e = wrapYNoteException(response); throw e; } return response; }
/** * Create a thread-safe client. This client does not do redirecting, to allow us to capture * correct "error" codes. * * @return HttpClient */ public static final DefaultHttpClient createHttpClient() { // Sets up the http part of the service. final SchemeRegistry supportedSchemes = new SchemeRegistry(); // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. final SocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", sf, 80)); // Set some client http client parameter defaults. final HttpParams httpParams = createHttpParams(); HttpClientParams.setRedirecting(httpParams, false); final ClientConnectionManager ccm = new ThreadSafeClientConnManager(httpParams, supportedSchemes); return new DefaultHttpClient(ccm, httpParams); }
public static AndroidHttpClient newInstance(String paramString, Context paramContext) { BasicHttpParams localBasicHttpParams = new BasicHttpParams(); HttpConnectionParams.setStaleCheckingEnabled(localBasicHttpParams, false); HttpConnectionParams.setConnectionTimeout(localBasicHttpParams, 20000); HttpConnectionParams.setSoTimeout(localBasicHttpParams, 20000); HttpConnectionParams.setSocketBufferSize(localBasicHttpParams, 8192); HttpClientParams.setRedirecting(localBasicHttpParams, false); if (paramContext == null) {} for (SSLSessionCache localSSLSessionCache = null;; localSSLSessionCache = new SSLSessionCache(paramContext)) { HttpProtocolParams.setUserAgent(localBasicHttpParams, paramString); SchemeRegistry localSchemeRegistry = new SchemeRegistry(); localSchemeRegistry.register(new Scheme("http", ElegantPlainSocketFactory.getSocketFactory(), 80)); localSchemeRegistry.register(new Scheme("https", getSocketFactory(localSSLSessionCache), 443)); ConnManagerParamBean localConnManagerParamBean = new ConnManagerParamBean(localBasicHttpParams); localConnManagerParamBean.setConnectionsPerRoute(new ConnPerRouteBean(4)); localConnManagerParamBean.setMaxTotalConnections(8); return new AndroidHttpClient(new ElegantThreadSafeConnManager(localBasicHttpParams, localSchemeRegistry), localBasicHttpParams); } }
public HttpClient getHttpClient() { // 创建 HttpParams 以用来设置 HTTP 参数(这一部分不是必需的) this.httpParams = new BasicHttpParams(); // 设置连接超时和 Socket 超时,以及 Socket 缓存大小 HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSocketBufferSize(httpParams, 8192); // 设置重定向,缺省为 true HttpClientParams.setRedirecting(httpParams, true); // 设置 user agent String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6"; HttpProtocolParams.setUserAgent(httpParams, userAgent); // 创建一个 HttpClient 实例 // 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient // 中的用法,在 Android 1.5 中我们需要使用 Apache 的缺省实现 DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); return httpClient; }
public CookieRestTemplate() { httpContext = new BasicHttpContext(); cookieStore = new BasicCookieStore(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); //REGISTERS SCHEMES FOR BOTH HTTP AND HTTPS SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory(); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); registry.register(new Scheme("https", sslSocketFactory, 443)); ClientConnectionManager conman = new ThreadSafeClientConnManager(params, registry); httpClient = new DefaultHttpClient(conman, params); HttpComponentsClientHttpRequestFactory hcchrf = new StatefulHttpComponentsClientHttpRequestFactory(httpClient, httpContext); hcchrf.setConnectTimeout(30 * 1000); setRequestFactory(hcchrf); }
public HttpClient getHttpClient() { // 鍒涘缓 HttpParams 浠ョ敤鏉ヨ缃� HTTP 鍙傛暟锛堣繖涓�閮ㄥ垎涓嶆槸蹇呴渶鐨勶級 HttpParams httpParams = new BasicHttpParams(); // 璁剧疆杩炴帴瓒呮椂鍜� Socket 瓒呮椂锛屼互鍙� Socket 缂撳瓨澶у皬 HttpConnectionParams.setConnectionTimeout(httpParams, 30 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 60 * 1000); HttpConnectionParams.setSocketBufferSize(httpParams, 8192); // 璁剧疆閲嶅畾鍚戯紝缂虹渷涓� true HttpClientParams.setRedirecting(httpParams, true); // 璁剧疆 user agent String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6"; HttpProtocolParams.setUserAgent(httpParams, userAgent); // 鍒涘缓涓�涓� HttpClient 瀹炰緥 // 娉ㄦ剰 HttpClient httpClient = new HttpClient(); 鏄疌ommons HttpClient // 涓殑鐢ㄦ硶锛屽湪 Android 1.5 涓垜浠渶瑕佷娇鐢� Apache 鐨勭己鐪佸疄鐜� DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); return httpClient; }
public static DefaultHttpClient createDefaultHttpClient(boolean threadSafe, boolean enableRedirect) { HttpParams httpParams = new BasicHttpParams(); HttpClientParams.setRedirecting(httpParams, enableRedirect); setTimeout(httpParams, Constants.HTTP_REQUEST_TIME_OUT * 1000); if (threadSafe) { SchemeRegistry supportedSchemes = new SchemeRegistry(); SocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", sf, 80)); ClientConnectionManager ccm = new ThreadSafeClientConnManager( httpParams, supportedSchemes); return new DefaultHttpClient(ccm, httpParams); } else { return new DefaultHttpClient(httpParams); } }
private HttpClient getHttpClient() { synchronized (mClientLock) { if ((null == mHttpClient) || mConnectionConfig.isFullAsync()) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, mConnectionConfig.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpParameters, mConnectionConfig.getReadTimeout()); HttpClientParams.setRedirecting(httpParameters, false); if (mConnectionConfig.getSchemeRegistry() != null) { ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(httpParameters, mConnectionConfig.getSchemeRegistry()); mHttpClient = new DefaultHttpClient(connectionManager, httpParameters); } else { mHttpClient = new DefaultHttpClient(httpParameters); } } return mHttpClient; } }
private BasicHttpParams initHttpParams() { BasicHttpParams params = new BasicHttpParams(); if (socketTimeout > -1) { HttpConnectionParams.setSoTimeout(params, (int) socketTimeoutUnits.toMillis(socketTimeout)); } if (establishConnectionTimeout > -1) { HttpConnectionParams.setConnectionTimeout(params, (int)establishConnectionTimeoutUnits.toMillis(establishConnectionTimeout) ); } if (connectionCheckoutTimeoutMs > -1) { HttpClientParams.setConnectionManagerTimeout(params, connectionCheckoutTimeoutMs); } return params; }
/** * Returns the HttpClient singleton. */ public static synchronized HttpClient getHttpClient() { if (httpClient == null) { if (AppConfig.DEBUG) Log.d(TAG, "Creating new instance of HTTP client"); HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.USER_AGENT, AppPreferences.USER_AGENT); params.setIntParameter("http.protocol.max-redirects", MAX_REDIRECTS); params.setBooleanParameter("http.protocol.reject-relative-redirect", false); HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT); HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT); HttpClientParams.setRedirecting(params, true); httpClient = new DefaultHttpClient(createClientConnectionManager(), params); // Workaround for broken URLs in redirection ((AbstractHttpClient) httpClient) .setRedirectHandler(new APRedirectHandler()); } return httpClient; }
/** * Create a thread-safe client. This client does not do redirecting, to allow us to capture * correct "error" codes. * * @return HttpClient */ public static final DefaultHttpClient createHttpClient(Context mContext) { // Sets up the http part of the service. final SchemeRegistry supportedSchemes = new SchemeRegistry(); // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. final SocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", sf, 80)); supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // Set some client http client parameter defaults. final HttpParams httpParams = createHttpParams(mContext); HttpClientParams.setRedirecting(httpParams, false); final ClientConnectionManager ccm = new ThreadSafeClientConnManager(httpParams, supportedSchemes); return new DefaultHttpClient(ccm, httpParams); }
private void createClient() { BasicHttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeoutMs); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeoutMs); HttpClientParams.setRedirecting(httpParams, allowRedirects); HttpClientParams.setConnectionManagerTimeout(httpParams, connectionManagerTimeoutMs); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry); connectionManager.setMaxTotal(maxConnections); connectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams); this.client = new HttpClient4Client(httpClient); }
private ConnectionHelper() { HttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(httpParams, MAX_TOTAL_CONNECTIONS); ConnPerRouteBean connPerRoute = new ConnPerRouteBean( MAX_CONNECTIONS_PER_HOST); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUseExpectContinue(httpParams, false); SchemeRegistry reg = new SchemeRegistry(); reg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); reg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager( httpParams, reg); HttpConnectionParams.setConnectionTimeout(httpParams, CON_TIME_OUT_MS); HttpConnectionParams.setSoTimeout(httpParams, SO_TIME_OUT_MS); HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.BROWSER_COMPATIBILITY); httpClient = new DefaultHttpClient(connectionManager, httpParams); }
/** * Reconfigures the HTTP client used for execution based on the variables * set in the HttpTransport.<br /> * <br /> * The HttpTransport variables include: <code>_connectionTimeout</code> * and <code>_socketIdleTimeout</code>. */ private void configureHttpClient() { HttpParams params = this._httpClient.getParams(); // Specify whether the Apache htto client should follow redirects automatically. // For frameworks like Spring WebFlow we DO NOT want the Apache client to // automatically follow redirects, rather we want HttpTransport to manually follow // redirects. // If HttpTransport isn't following, then let Apache Http client do it if( this._followRedirects ) HttpClientParams.setRedirecting( params, false ); else HttpClientParams.setRedirecting( params, true ); HttpConnectionParams.setConnectionTimeout( params, this._connectTimeout ); HttpConnectionParams.setSoTimeout( params, this._socketIdleTimeout ); }
/** * initialize http client */ public DownloadService() { // HttpParams params = new BasicHttpParams(); // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // HttpProtocolParams.setUseExpectContinue(params, false); // ConnManagerParams.setMaxTotalConnections(params, 10); // HttpConnectionParams.setConnectionTimeout(params, 10 * 1000); // HttpConnectionParams.setSoTimeout(params, 10 * 1000); // // SchemeRegistry schReg = new SchemeRegistry(); // schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); httpClient = AndroidHttpClient.newInstance("stockanalyze,gzip"); HttpClientParams.setRedirecting(httpClient.getParams(), true); }
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); }
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; }
public HttpResponse postMessage(MultipartEntity entity, String board) { HttpPost p = new HttpPost(String.format(DobroConstants.POST_NEW, board)); final HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); ConnManagerParams.setTimeout(params, 20000); HttpConnectionParams.setSoTimeout(params, 20000); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSocketBufferSize(params, 8192); p.setParams(params); p.setEntity(entity); try { HttpResponse r = m_httpclient.execute(p, m_http_context); p.abort(); return r; } catch (IOException e) { e.printStackTrace(); } return null; }
static private DefaultHttpClient setupHttpClient() { HttpParams connectionParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(connectionParams, 30000); // thirty seconds HttpConnectionParams.setSoTimeout(connectionParams, 30000); HttpClientParams.setRedirecting(connectionParams, false); DefaultHttpClient client = new DefaultHttpClient(connectionParams); client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } } }); return client; }
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); }
public HttpStoreClientFactory(ClientConfig config) { super(config); ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(SchemeRegistryFactory.createDefault(), config.getConnectionTimeout(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); mgr.setMaxTotal(config.getMaxTotalConnections()); mgr.setDefaultMaxPerRoute(config.getMaxConnectionsPerNode()); this.httpClient = new DefaultHttpClient(mgr); HttpParams clientParams = this.httpClient.getParams(); HttpProtocolParams.setUserAgent(clientParams, VOLDEMORT_USER_AGENT); HttpProtocolParams.setVersion(clientParams, HttpVersion.HTTP_1_1); HttpConnectionParams.setConnectionTimeout(clientParams, config.getConnectionTimeout(TimeUnit.MILLISECONDS)); HttpConnectionParams.setSoTimeout(clientParams, config.getSocketTimeout(TimeUnit.MILLISECONDS)); HttpConnectionParams.setStaleCheckingEnabled(clientParams, false); this.httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); HttpClientParams.setCookiePolicy(clientParams, CookiePolicy.IGNORE_COOKIES); this.reroute = config.getRoutingTier().equals(RoutingTier.SERVER); this.requestFormatFactory = new RequestFormatFactory(); }
private ResponseImpl getWebContentPrivate(Request request, @Nullable ProxyDetails proxy, boolean followRedirects) { final String url = request.getUrl(); try { @SuppressWarnings("unused") URL u = new URL(url); // NOSONAR } catch( MalformedURLException ex ) { return new ResponseImpl(HttpServletResponse.SC_BAD_REQUEST, "Invalid URL: " + url); } HttpRequestBase httpMethod = null; try { httpMethod = getHttpMethod(request); if( httpMethod == null ) { return new ResponseImpl(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Only GET, POST, HEAD, PUT, DELETE and OPTIONS methods are supported"); } if( !followRedirects ) { HttpClientParams.setRedirecting(httpMethod.getParams(), false); } final DefaultHttpClient client = createClient(httpMethod.getURI().getScheme().equals("https")); if( proxy != null && proxy.isConfigured() ) { final URI uri = httpMethod.getURI(); final String host = uri.getHost(); if( !proxy.isHostExcepted(host) ) { final HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort()); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost); if( !Check.isEmpty(proxy.getUsername()) ) { client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword())); } } } // TODO: see fixme about cookie cache final String cacheKey = /* req.getSession().getId() */"FIXME" + ':' + url; Cookies cookies = COOKIE_CACHE.getIfPresent(cacheKey); if( cookies == null ) { cookies = new Cookies(); COOKIE_CACHE.put(cacheKey, cookies); } final HttpResponse response = exec(client, httpMethod, cookies); return new ResponseImpl(response, httpMethod); } catch( Exception e ) { throw new RuntimeException(e); } }
public static b a() { if (b == null) { HttpParams basicHttpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(basicHttpParams, HttpVersion.HTTP_1_1); HttpConnectionParams.setStaleCheckingEnabled(basicHttpParams, true); basicHttpParams.setBooleanParameter("http.protocol.expect-continue", false); ConnManagerParams.setMaxTotalConnections(basicHttpParams, 50); ConnManagerParams.setMaxConnectionsPerRoute(basicHttpParams, new ConnPerRouteBean(30)); ConnManagerParams.setTimeout(basicHttpParams, 1000); HttpConnectionParams.setConnectionTimeout(basicHttpParams, 20000); HttpConnectionParams.setSoTimeout(basicHttpParams, 30000); HttpConnectionParams.setSocketBufferSize(basicHttpParams, 16384); HttpProtocolParams.setUseExpectContinue(basicHttpParams, false); HttpClientParams.setRedirecting(basicHttpParams, true); HttpClientParams.setAuthenticating(basicHttpParams, false); HttpProtocolParams.setUserAgent(basicHttpParams, a); try { SocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); socketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme scheme = new Scheme(com.alipay.sdk.cons.b.a, socketFactory, WebSocket.DEFAULT_WSS_PORT); Scheme scheme2 = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(scheme); schemeRegistry.register(scheme2); b = new b(new ThreadSafeClientConnManager(basicHttpParams, schemeRegistry), basicHttpParams); } catch (Exception e) { b = new b(basicHttpParams); } } return b; }
/** * @param username * the username to use, can be null to avoid adding user name and password * @param password * the password to use * @return the http client configured with username and password */ private HttpClient configureHttpClient(String username, String password) { DefaultHttpClient httpClient = new DefaultHttpClient(); if (username != null) { Credentials defaultcreds = new UsernamePasswordCredentials(username, password); httpClient.getCredentialsProvider().setCredentials( new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds); HttpClientParams.setAuthenticating(httpClient.getParams(), true); } HttpClientParams.setRedirecting(httpClient.getParams(), false); return httpClient; }
/** * HTTP参数配置 * @return */ public BasicHttpParams getHttpParams(){ BasicHttpParams httpParams = new BasicHttpParams(); // 设置每个路由最大连接数 ConnPerRouteBean connPerRoute = new ConnPerRouteBean(30); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute); HttpConnectionParams.setStaleCheckingEnabled(httpParams, false); // 从连接池中取连接的超时时间,设置为1秒 ConnManagerParams.setTimeout(httpParams, mTimeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); // 读响应数据的超时时间 HttpConnectionParams.setSoTimeout(httpParams, mTimeout); HttpConnectionParams.setConnectionTimeout(httpParams, mTimeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams,userAgent); //默认参数 HttpClientParams.setRedirecting(httpParams, false); HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.BROWSER_COMPATIBILITY); httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); return httpParams; }
/** * Create a new HttpClient with reasonable defaults (which you can update). * * @param userAgent to report in your HTTP requests. * @return AndroidHttpClient for you to use for all your requests. */ public static AndroidHttpClient newInstance(String userAgent) { 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); // Default connection and socket timeout of 20 seconds. Tweak to taste. HttpConnectionParams.setConnectionTimeout(params, 20 * 1000); HttpConnectionParams.setSoTimeout(params, 20 * 1000); 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); // 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", SSLSocketFactory.getSocketFactory(), 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); }
private static void configureHttpClient(HttpClient httpClient) { HttpParams params = httpClient.getParams(); HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONNECT_TIMEOUT_MILLIS); HttpConnectionParams.setSoTimeout(params, DEFAULT_READ_TIMEOUT_MILLIS); HttpConnectionParams.setSocketBufferSize(params, 8192); ConnManagerParams.setTimeout(params, DEFAULT_GET_CONNECTION_FROM_POOL_TIMEOUT_MILLIS); // Don't handle redirects automatically HttpClientParams.setRedirecting(params, false); // Don't handle authentication automatically HttpClientParams.setAuthenticating(params, false); }
public void testClientConfiguration() throws Exception { HttpParams params = mClient.getParams(); assertFalse(HttpClientParams.isRedirecting(params)); assertFalse(HttpClientParams.isAuthenticating(params)); assertEquals( HttpClientFactory.DEFAULT_CONNECT_TIMEOUT_MILLIS, HttpConnectionParams.getConnectionTimeout(params)); assertEquals( HttpClientFactory.DEFAULT_READ_TIMEOUT_MILLIS, HttpConnectionParams.getSoTimeout(params)); assertEquals( HttpClientFactory.DEFAULT_GET_CONNECTION_FROM_POOL_TIMEOUT_MILLIS, ConnManagerParams.getTimeout(params)); }
public static AndroidHttpClient getHttpClient() { final String userAgent = getWebViewUserAgent(DEFAULT_USER_AGENT); AndroidHttpClient httpClient = AndroidHttpClient.newInstance(userAgent); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT); HttpClientParams.setRedirecting(params, true); return httpClient; }
/** * Private constructor. To get an instance use {@link #getInstance()} * @see AndroidHttpClient */ private SimpleHttpClient() { mClient = AndroidHttpClient.newInstance(USER_AGENT); HttpParams params = mClient.getParams(); HttpClientParams.setRedirecting(params, true); mCookieStore = new PersistentCookieStore(); mHttpContext = new BasicHttpContext(); mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore); }
/** * * @param isMultiRequest * 是否支持多线程 * @param connectionTimeout * 建立连接超时时间(毫秒) * @param socketTimeout * 等待数据超时时间(毫秒) * @return */ public static HttpClient getHttpClient(boolean isMultiRequest, int connectionTimeout, int socketTimeout) { SchemeRegistry schemeRegistry = SchemeRegistryFactory.createDefault(); ClientConnectionManager cm = isMultiRequest ? new PoolingClientConnectionManager( schemeRegistry) : new BasicClientConnectionManager( schemeRegistry); HttpParams params = isMultiRequest ? new SyncBasicHttpParams() : new BasicHttpParams(); HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY); HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); HttpConnectionParams.setSoTimeout(params, socketTimeout); return new DefaultHttpClient(cm, params); }