protected HttpClient constructHttpClient() { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpClient httpClient = new HttpClient(connectionManager); HttpClientParams params = httpClient.getParams(); params.setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true); params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true); if (socketTimeout != null) { params.setSoTimeout(socketTimeout); } HttpConnectionManagerParams connectionManagerParams = httpClient.getHttpConnectionManager().getParams(); connectionManagerParams.setMaxTotalConnections(maxTotalConnections); connectionManagerParams.setDefaultMaxConnectionsPerHost(maxHostConnections); connectionManagerParams.setConnectionTimeout(connectionTimeout); return httpClient; }
private static byte[] executeMethod(HttpMethodBase method, int timeout) throws Exception { InputStream in = null; try { method.addRequestHeader("Connection", "close"); HttpClient client = new HttpClient(); HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams(); params.setConnectionTimeout(timeout); params.setSoTimeout(timeout); params.setStaleCheckingEnabled(false); ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE); client.executeMethod(method); in = method.getResponseBodyAsStream(); byte[] buffer = new byte[BUFFER_SIZE]; int len; while( (len = in.read(buffer)) > 0) { baos.write(buffer, 0, len); } return baos.toByteArray(); } finally { if (in != null) { in.close(); } } }
private static boolean pageExists(@NotNull String url) { if (new File(url).exists()) { return true; } final HttpClient client = new HttpClient(); final HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams(); params.setSoTimeout(5 * 1000); params.setConnectionTimeout(5 * 1000); try { final HeadMethod method = new HeadMethod(url); final int rc = client.executeMethod(method); if (rc == 404) { return false; } } catch (IllegalArgumentException e) { return false; } catch (IOException ignored) { } return true; }
/** * @param multiThreadedHttpConnectionManager * The * @link {@link MultiThreadedHttpConnectionManager} that the fulltext search * engine will use * @throws FullTextSearchException * If an error occured */ @Autowired public FullTextSearchEngine( @Qualifier("multiThreadedHttpConnectionManager") MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager) throws FullTextSearchException { Assert.notNull(multiThreadedHttpConnectionManager, "multiThreadedHttpConnectionManager can not be null"); HttpConnectionManagerParams p = new HttpConnectionManagerParams(); p.setSoTimeout(0); p.setConnectionTimeout(0); multiThreadedHttpConnectionManager.setParams(p); this.httpClient = new HttpClient(multiThreadedHttpConnectionManager); if (this.httpClient == null) { throw new FullTextSearchException( "Can not instanciate http client with multiThreadedHttpConnectionManager : " + multiThreadedHttpConnectionManager); } }
/** * * @throws Exception . */ private void init() throws Exception { httpClientManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = httpClientManager.getParams(); params.setStaleCheckingEnabled(true); params.setMaxTotalConnections(1000); params.setDefaultMaxConnectionsPerHost(500); params.setConnectionTimeout(2000); params.setSoTimeout(3000); /** 设置从连接池中获取连接超时。*/ HttpClientParams clientParams = new HttpClientParams(); clientParams.setConnectionManagerTimeout(1000); httpClient = new HttpClient(clientParams, httpClientManager); }
public HttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize) { connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = connectionManager.getParams(); params.setDefaultMaxConnectionsPerHost(maxConPerHost); params.setConnectionTimeout(conTimeOutMs); params.setSoTimeout(soTimeOutMs); HttpClientParams clientParams = new HttpClientParams(); // 忽略cookie 避免 Cookie rejected 警告 clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); client = new org.apache.commons.httpclient.HttpClient(clientParams, connectionManager); Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); this.maxSize = maxSize; // 支持proxy if (proxyHost != null && !proxyHost.equals("")) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); client.getParams().setAuthenticationPreemptive(true); if (proxyAuthUser != null && !proxyAuthUser.equals("")) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyAuthUser, proxyAuthPassword)); log("Proxy AuthUser: " + proxyAuthUser); log("Proxy AuthPassword: " + proxyAuthPassword); } } }
public HttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize) { // MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager(true); HttpConnectionManagerParams params = connectionManager.getParams(); params.setDefaultMaxConnectionsPerHost(maxConPerHost); params.setConnectionTimeout(conTimeOutMs); params.setSoTimeout(soTimeOutMs); HttpClientParams clientParams = new HttpClientParams(); clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); client = new org.apache.commons.httpclient.HttpClient(clientParams, connectionManager); Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); }
/** * Load proxy configuration when proxy config has changed */ private void loadProxyConfig(){ connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setSoTimeout(proxyConfig.getSoTimeout()); params.setConnectionTimeout(proxyConfig.getConnectionTimeout()); params.setMaxTotalConnections(proxyConfig.getMaxTotalConnections()); params.setDefaultMaxConnectionsPerHost(proxyConfig .getDefaultMaxConnectionsPerHost()); connectionManager.setParams(params); httpClient = new HttpClient(connectionManager); configureCallbacks(); }
/** * Define client configuration * @param httpClient instance to configure */ private static void setConfiguration(final HttpClient httpClient) { final HttpConnectionManagerParams httpParams = httpClient.getHttpConnectionManager().getParams(); // define connect timeout: httpParams.setConnectionTimeout(NetworkSettings.DEFAULT_CONNECT_TIMEOUT); // define read timeout: httpParams.setSoTimeout(NetworkSettings.DEFAULT_SOCKET_READ_TIMEOUT); // define connection parameters: httpParams.setMaxTotalConnections(NetworkSettings.DEFAULT_MAX_TOTAL_CONNECTIONS); httpParams.setDefaultMaxConnectionsPerHost(NetworkSettings.DEFAULT_MAX_HOST_CONNECTIONS); // set content-encoding to UTF-8 instead of default ISO-8859 final HttpClientParams httpClientParams = httpClient.getParams(); // define timeout value for allocation of connections from the pool httpClientParams.setConnectionManagerTimeout(NetworkSettings.DEFAULT_CONNECT_TIMEOUT); // encoding to UTF-8 httpClientParams.setParameter(HttpClientParams.HTTP_CONTENT_CHARSET, "UTF-8"); // avoid retries (3 by default): httpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER, _httpNoRetryHandler); // Customize the user agent: httpClientParams.setParameter(HttpMethodParams.USER_AGENT, System.getProperty(NetworkSettings.PROPERTY_USER_AGENT)); }
@Override public void init(ServletConfig config) throws ServletException { super.init(config); // Create a pool of HTTP connections to use to get the favicons client = new HttpClient(new MultiThreadedHttpConnectionManager()); HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams(); params.setConnectionTimeout(2000); params.setSoTimeout(2000); // Load the default favicon to use when no favicon was found of a remote host try { URL resource = config.getServletContext().getResource("/images/server_16x16.gif"); defaultBytes = getImage(resource.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } // Initialize caches. missesCache = CacheFactory.createCache("Favicon Misses"); hitsCache = CacheFactory.createCache("Favicon Hits"); }
/** * * Public Section * */ public void connectHTTP(String strUser, String strPass, String strHost, boolean insecure) { //Connect WebDAV with credentials hostConfig = new HostConfiguration(); hostConfig.setHost(strHost); connectionManager = new MultiThreadedHttpConnectionManager(); connectionManagerParams = new HttpConnectionManagerParams(); connectionManagerParams.setMaxConnectionsPerHost(hostConfig, this.intMaxConnections); connectionManager.setParams(connectionManagerParams); client = new HttpClient(connectionManager); creds = new UsernamePasswordCredentials(strUser, strPass); client.getState().setCredentials(AuthScope.ANY, creds); client.setHostConfiguration(hostConfig); if (insecure) { Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443); Protocol.registerProtocol("https", easyhttps); } Status.print("WebDav Connection generated"); }
@NotNull private static HttpClient getHttpClient(@Nullable GithubAuthData.BasicAuth basicAuth) { final HttpClient client = new HttpClient(); HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams(); params.setConnectionTimeout(CONNECTION_TIMEOUT); //set connection timeout (how long it takes to connect to remote host) params.setSoTimeout(CONNECTION_TIMEOUT); //set socket timeout (how long it takes to retrieve data from remote host) client.getParams().setContentCharset("UTF-8"); // Configure proxySettings if it is required final HttpConfigurable proxySettings = HttpConfigurable.getInstance(); if (proxySettings.USE_HTTP_PROXY && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)) { client.getHostConfiguration().setProxy(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT); if (proxySettings.PROXY_AUTHENTICATION) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxySettings.PROXY_LOGIN, proxySettings.getPlainProxyPassword())); } } if (basicAuth != null) { client.getParams().setCredentialCharset("UTF-8"); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(basicAuth.getLogin(), basicAuth.getPassword())); } return client; }
public RobotsTxtParser(int timeout, int cacheSize) { robotsTxtCache = ExpiringLRUMap.create(cacheSize); int timeToWaitForResponse = (int) (timeout * DateUtils.MILLIS_PER_SECOND); HttpConnectionManagerParams hmcp = new HttpConnectionManagerParams(); hmcp.setSoTimeout(timeToWaitForResponse); hmcp.setConnectionTimeout(timeToWaitForResponse); hcm = new MultiThreadedHttpConnectionManager(); hcm.setParams(hmcp); client = new HttpClient(hcm); String proxyHost = FWProps.getStringProperty("http.proxyHost"); int proxyPort = FWProps.getIntegerProperty("http.proxyPort"); if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); } }
protected void configureDefaultHttpClientParams(HttpParams params) { params.setParameter(HttpClientParams.CONNECTION_MANAGER_CLASS, MultiThreadedHttpConnectionManager.class); params.setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109); params.setLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, 10000); Map<HostConfiguration, Integer> maxHostConnectionsMap = new HashMap<HostConfiguration, Integer>(); maxHostConnectionsMap.put(HostConfiguration.ANY_HOST_CONFIGURATION, new Integer(20)); params.setParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, maxHostConnectionsMap); params.setIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, 20); params.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 10000); params.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 2*60*1000); boolean retrySocketException = new Boolean(ConfigContext.getCurrentContextConfig().getProperty(RETRY_SOCKET_EXCEPTION_PROPERTY)); if (retrySocketException) { LOG.info("Installing custom HTTP retry handler to retry requests in face of SocketExceptions"); params.setParameter(HttpMethodParams.RETRY_HANDLER, new CustomHttpMethodRetryHandler()); } }
/** * Init the parameter settings for the http client */ private HttpConnectionManagerParams connectionParams() { HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setDefaultMaxConnectionsPerHost(readMaxHostConnectionSetting()); params.setMaxTotalConnections(readMaxTotalConnectionSetting()); return params; }
private HttpClient createHttpClient() { HttpClient client = new HttpClient(); // added by Unicon to handle proxy hosts String proxyHost = System.getProperty( "http.proxyHost" ); if ( proxyHost != null ) { int proxyPort = -1; String proxyPortStr = System.getProperty( "http.proxyPort" ); if (proxyPortStr != null) { try { proxyPort = Integer.parseInt( proxyPortStr ); } catch (NumberFormatException e) { logger.warn("Invalid number for system property http.proxyPort ("+proxyPortStr+"), using default port instead"); } } ProxyHost proxy = new ProxyHost( proxyHost, proxyPort ); client.getHostConfiguration().setProxyHost( proxy ); } // added by Unicon to force encoding to UTF-8 client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, UTF8_CHARSET); client.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, UTF8_CHARSET); client.getParams().setParameter(HttpMethodParams.HTTP_URI_CHARSET, UTF8_CHARSET); HttpConnectionManagerParams connParams = client.getHttpConnectionManager().getParams(); if(this.kalturaConfiguration.getTimeout() != 0) { connParams.setSoTimeout(this.kalturaConfiguration.getTimeout()); connParams.setConnectionTimeout(this.kalturaConfiguration.getTimeout()); } client.getHttpConnectionManager().setParams(connParams); return client; }
public Stubs(ConfigurationContext ctx, String bbUrl) throws AxisFault { this.ctx = ctx; this.bbUrl = bbUrl; /* * Must use deprecated class of setting up security because the SOAP * response doesn't include a security header. Using the deprecated * OutflowConfiguration class we can specify that the security * header is only for the outgoing SOAP message. */ ofc = new OutflowConfiguration(); ofc.setActionItems("UsernameToken Timestamp"); ofc.setUser("session"); ofc.setPasswordType("PasswordText"); final MultiThreadedHttpConnectionManager conMan = new MultiThreadedHttpConnectionManager(); final HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setMaxTotalConnections(1000); params.setDefaultMaxConnectionsPerHost(100); params.setSoTimeout(60000); params.setConnectionTimeout(30000); conMan.setParams(params); httpClient = new HttpClient(conMan); final HttpClientParams clientParams = httpClient.getParams(); clientParams.setAuthenticationPreemptive(false); clientParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); ctx.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient); contextWebservice = new ContextWSStub(ctx, PathUtils.filePath(bbUrl, "webapps/ws/services/Context.WS")); initStub(contextWebservice); }
/** * Builds an HTTP client with the given settings. Settings are NOT reset to their default values after a client has * been created. * * @return the created client. */ public HttpClient buildClient() { if (httpsProtocolSocketFactory != null) { Protocol.registerProtocol("https", new Protocol("https", httpsProtocolSocketFactory, 443)); } HttpClientParams clientParams = new HttpClientParams(); clientParams.setAuthenticationPreemptive(isPreemptiveAuthentication()); clientParams.setContentCharset(getContentCharSet()); clientParams.setParameter(HttpClientParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler( connectionRetryAttempts, false)); HttpConnectionManagerParams connMgrParams = new HttpConnectionManagerParams(); connMgrParams.setConnectionTimeout(getConnectionTimeout()); connMgrParams.setDefaultMaxConnectionsPerHost(getMaxConnectionsPerHost()); connMgrParams.setMaxTotalConnections(getMaxTotalConnections()); connMgrParams.setReceiveBufferSize(getReceiveBufferSize()); connMgrParams.setSendBufferSize(getSendBufferSize()); connMgrParams.setTcpNoDelay(isTcpNoDelay()); MultiThreadedHttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager(); connMgr.setParams(connMgrParams); HttpClient httpClient = new HttpClient(clientParams, connMgr); if (proxyHost != null) { HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setProxy(proxyHost, proxyPort); httpClient.setHostConfiguration(hostConfig); if (proxyUsername != null) { AuthScope proxyAuthScope = new AuthScope(proxyHost, proxyPort); UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(proxyUsername, proxyPassword); httpClient.getState().setProxyCredentials(proxyAuthScope, proxyCredentials); } } return httpClient; }
public SharedHttpClientProvider(String alfrescoUrl, int maxNumberOfConnections) { setAlfrescoUrl(alfrescoUrl); // Initialize manager MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setMaxTotalConnections(maxNumberOfConnections); params.setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, maxNumberOfConnections); // Create the client client = new HttpClient(manager); client.getParams().setAuthenticationPreemptive(true); }
private void initialize(Cluster cluster, boolean sslEnabled) { this.cluster = cluster; this.sslEnabled = sslEnabled; MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams managerParams = manager.getParams(); managerParams.setConnectionTimeout(2000); // 2 s managerParams.setDefaultMaxConnectionsPerHost(10); managerParams.setMaxTotalConnections(100); extraHeaders = new ConcurrentHashMap<String, String>(); this.httpClient = new HttpClient(manager); HttpClientParams clientParams = httpClient.getParams(); clientParams.setVersion(HttpVersion.HTTP_1_1); }
/** * GET请求 * * @param url 请求url * @return 返回请求结果 */ public static String doGet(String url) { HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); String result = ""; try { method.setRequestHeader("Content-Type", "text/html;charset=utf-8"); //设置页面编码 method.getParams().setContentCharset("UTF-8"); HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams(); // 设置连接超时时间(单位毫秒) managerParams.setConnectionTimeout(CONN_TIME_OUT); // 设置读数据超时时间(单位毫秒) managerParams.setSoTimeout(SO_TIME_OUT); client.executeMethod(method); //获取返回的JSON数据 result = method.getResponseBodyAsString(); } catch (Exception e) { log.error("GET请求发生系统异常:", e); } finally { try { // 释放连接 method.releaseConnection(); } catch (Exception ex) { } } return result; }
private static byte[] executeMethod(HttpMethodBase method, int timeout) throws Exception { InputStream in = null; try { method.addRequestHeader("Connection", "close"); HttpClient client = new HttpClient(); HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams(); //设置连接时候一些参数 params.setConnectionTimeout(timeout); params.setSoTimeout(timeout); params.setStaleCheckingEnabled(false); ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE); int stat = client.executeMethod(method); if (stat != HttpStatus.SC_OK) log.error("get失败!"); //method.getResponseBody() in = method.getResponseBodyAsStream(); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = in.read(buffer)) > 0) { baos.write(buffer, 0, len); } return baos.toByteArray(); } finally { if (in != null) { in.close(); } } }
private void initHttpClient() { HostConfiguration hostConfiguration = new HostConfiguration(); SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager(); connectionManager.closeIdleConnections(5000L); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setStaleCheckingEnabled(diamondConfigure.isConnectionStaleCheckingEnabled()); params.setConnectionTimeout(diamondConfigure.getConnectionTimeout()); connectionManager.setParams(params); configHttpClient = new HttpClient(connectionManager); configHttpClient.setHostConfiguration(hostConfiguration); }
public HttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize) { connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = connectionManager.getParams(); params.setDefaultMaxConnectionsPerHost(maxConPerHost); params.setConnectionTimeout(conTimeOutMs); params.setSoTimeout(soTimeOutMs); HttpClientParams clientParams = new HttpClientParams(); // 忽略cookie 避免 Cookie rejected 警告 clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); client = new org.apache.commons.httpclient.HttpClient(clientParams, connectionManager); Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); this.maxSize = maxSize; // 支持proxy if (proxyHost != null && !proxyHost.equals("")) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); client.getParams().setAuthenticationPreemptive(true); if (proxyAuthUser != null && !proxyAuthUser.equals("")) { client.getState().setProxyCredentials( AuthScope.ANY, new UsernamePasswordCredentials(proxyAuthUser, proxyAuthPassword)); log("Proxy AuthUser: " + proxyAuthUser); log("Proxy AuthPassword: " + proxyAuthPassword); } } }
public void RequestConnectionHttp(String url, String user, String pass, int timeout) throws Exception { HttpClient client = new HttpClient(); HttpConnectionManager hcm = client.getHttpConnectionManager(); HttpConnectionManagerParams hcmParam = hcm.getParams(); hcmParam.setConnectionTimeout(timeout + 1000); hcm.setParams(hcmParam); client.setHttpConnectionManager(hcm); if (user != null && pass != null) { client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass)); } GetMethod get = new GetMethod(url); get.setDoAuthentication(true); try { int status = client.executeMethod(get); if (status != 200) { System.out.println(status + "\n" + get.getResponseBodyAsString()); throw new Exception("Failed: status=" + status); } setLastcrres("OK"); } catch (Exception e) { setLastcrres(e.getMessage()); System.out.println("HTTP CR OOPS: " + e.getMessage() + "\n"); throw e; } finally { get.releaseConnection(); } }
/** * Constructor * @param cluster the cluster definition */ public Client(Cluster cluster) { this.cluster = cluster; MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams managerParams = manager.getParams(); managerParams.setConnectionTimeout(2000); // 2 s managerParams.setDefaultMaxConnectionsPerHost(10); managerParams.setMaxTotalConnections(100); extraHeaders = new ConcurrentHashMap<String, String>(); this.httpClient = new HttpClient(manager); HttpClientParams clientParams = httpClient.getParams(); clientParams.setVersion(HttpVersion.HTTP_1_1); }
/** * Creates an instance of MultiThreadedHttpConnectionManager using HttpClient 3.x APIs * * @param properties Properties to configure MultiThreadedHttpConnectionManager * @return An instance of properly configured MultiThreadedHttpConnectionManager */ private HttpConnectionManager createConnectionManager(Properties properties) { HttpConnectionManagerParams params = new HttpConnectionManagerParams(); if (properties == null || properties.isEmpty()) { throw new IllegalArgumentException("Parameters required to initialize HttpClient instances " + "associated with OAuth token validation service stub are not provided"); } String maxConnectionsPerHostParam = properties.getProperty("MaxConnectionsPerHost"); if (maxConnectionsPerHostParam == null || maxConnectionsPerHostParam.isEmpty()) { if (log.isDebugEnabled()) { log.debug("MaxConnectionsPerHost parameter is not explicitly defined. Therefore, the default, " + "which is 2, will be used"); } } else { params.setDefaultMaxConnectionsPerHost(Integer.parseInt(maxConnectionsPerHostParam)); } String maxTotalConnectionsParam = properties.getProperty("MaxTotalConnections"); if (maxTotalConnectionsParam == null || maxTotalConnectionsParam.isEmpty()) { if (log.isDebugEnabled()) { log.debug("MaxTotalConnections parameter is not explicitly defined. Therefore, the default, " + "which is 10, will be used"); } } else { params.setMaxTotalConnections(Integer.parseInt(maxTotalConnectionsParam)); } HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.setParams(params); return connectionManager; }
public static HttpClient createHttpClient() { HttpClient result = null; try { result = new HttpClient(); // 使用多緒HttpClient MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams managerParams = httpConnectionManager .getParams(); managerParams.setDefaultMaxConnectionsPerHost(100); managerParams.setMaxTotalConnections(200); // 連線超時 managerParams.setConnectionTimeout(5 * 1000); // 讀取超時 managerParams.setSoTimeout(5 * 1000); // result.setHttpConnectionManager(httpConnectionManager); // HttpClientParams params = result.getParams(); // http.protocol.content-charset params.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); // 失敗 retry 3 次 params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); } catch (Exception ex) { ex.printStackTrace(); } return result; }