下面列出了怎么用org.apache.commons.httpclient.MultiThreadedHttpConnectionManager的API类实例代码及写法,或者点击链接到github查看源代码。
private void initConfigurationContext() throws Exception {
HttpConnectionManager multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager();
HttpClient httpClient = new HttpClient(multiThreadedHttpConnectionManager);
File configFile = new File(DEFAULT_AXIS2_XML);
if (!configFile.exists()) {
configurationContext = ConfigurationContextFactory.createDefaultConfigurationContext();
configurationContext.setProperty(HTTPConstants.DEFAULT_MAX_CONNECTIONS_PER_HOST, MAX_CONNECTIONS_PER_HOST);
} else {
configurationContext = ConfigurationContextFactory.
createConfigurationContextFromFileSystem(DEFAULT_CLIENT_REPO, DEFAULT_AXIS2_XML);
}
configurationContext.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
configurationContext.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE);
Map<String, TransportOutDescription> transportsOut = configurationContext.getAxisConfiguration()
.getTransportsOut();
for (TransportOutDescription transportOutDescription : transportsOut.values()) {
if (Constants.TRANSPORT_HTTP.equals(transportOutDescription.getName()) || Constants.TRANSPORT_HTTPS
.equals(transportOutDescription.getName())) {
transportOutDescription.getSender().init(configurationContext, transportOutDescription);
}
}
}
private RemoteLogRepositoryBackend()
{
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(CONCURENT_HTTP_CONNECTIONS);
/*for (int i = 0; i < CONCURENT_HTTP_CONNECTIONS; i++)
{
HttpConnection httpConn = new HttpConnection(REPOSITORY_HOST_ADDRESS, REPOSITORY_HOST_PORT);
httpConn.setHttpConnectionManager(connectionManager);
}*/
_httpClient = new HttpClient(connectionManager);
/*HostConfiguration hc = new HostConfiguration();
hc.setHost(REPOSITORY_HOST_ADDRESS, REPOSITORY_HOST_PORT);
_httpClient.setHostConfiguration(hc);*/
_dlQueue = new DownloadQueue(CONCURENT_DOWNLOADS);
_upQueue = new UploadQueue(CONCURENT_UPLOADS);
}
public HttpClientTransmitterImpl()
{
protocolMap = new TreeMap<String,Protocol>();
protocolMap.put(HTTP_SCHEME_NAME, httpProtocol);
protocolMap.put(HTTPS_SCHEME_NAME, httpsProtocol);
httpClient = new HttpClient();
httpClient.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
httpMethodFactory = new StandardHttpMethodFactoryImpl();
jsonErrorSerializer = new ExceptionJsonSerializer();
// Create an HTTP Proxy Host if appropriate system properties are set
httpProxyHost = HttpClientHelper.createProxyHost("http.proxyHost", "http.proxyPort", DEFAULT_HTTP_PORT);
httpProxyCredentials = HttpClientHelper.createProxyCredentials("http.proxyUser", "http.proxyPassword");
httpAuthScope = createProxyAuthScope(httpProxyHost);
// Create an HTTPS Proxy Host if appropriate system properties are set
httpsProxyHost = HttpClientHelper.createProxyHost("https.proxyHost", "https.proxyPort", DEFAULT_HTTPS_PORT);
httpsProxyCredentials = HttpClientHelper.createProxyCredentials("https.proxyUser", "https.proxyPassword");
httpsAuthScope = createProxyAuthScope(httpsProxyHost);
}
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;
}
public DiamondSDKManagerImpl(int connection_timeout, int require_timeout) throws IllegalArgumentException {
if (connection_timeout < 0)
throw new IllegalArgumentException("连接超时时间设置必须大于0[单位(毫秒)]!");
if (require_timeout < 0)
throw new IllegalArgumentException("请求超时时间设置必须大于0[单位(毫秒)]!");
this.connection_timeout = connection_timeout;
this.require_timeout = require_timeout;
int maxHostConnections = 50;
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxHostConnections);
connectionManager.getParams().setStaleCheckingEnabled(true);
this.client = new HttpClient(connectionManager);
// 设置连接超时时间
client.getHttpConnectionManager().getParams().setConnectionTimeout(this.connection_timeout);
// 设置读超时为1分钟
client.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);
client.getParams().setContentCharset("GBK");
log.info("设置连接超时时间为: " + this.connection_timeout + "毫秒");
}
protected void initHttpClient() {
if (MockServer.isTestMode()) {
return;
}
HostConfiguration hostConfiguration = new HostConfiguration();
hostConfiguration.setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
diamondConfigure.getPort());
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.closeIdleConnections(diamondConfigure.getPollingIntervalTime() * 4000);
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
params.setStaleCheckingEnabled(diamondConfigure.isConnectionStaleCheckingEnabled());
params.setMaxConnectionsPerHost(hostConfiguration, diamondConfigure.getMaxHostConnections());
params.setMaxTotalConnections(diamondConfigure.getMaxTotalConnections());
params.setConnectionTimeout(diamondConfigure.getConnectionTimeout());
// 设置读超时为1分钟,
// [email protected]
params.setSoTimeout(60 * 1000);
connectionManager.setParams(params);
httpClient = new HttpClient(connectionManager);
httpClient.setHostConfiguration(hostConfiguration);
}
public static InputStream getInputStreamFromUrl(final String url, final String user, final String password) {
try {
final Pair<String, Integer> hostAndPort = validateUrl(url);
final HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
if ((user != null) && (password != null)) {
httpclient.getParams().setAuthenticationPreemptive(true);
final Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
}
// Execute the method.
final GetMethod method = new GetMethod(url);
final int statusCode = httpclient.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
s_logger.error("Failed to read from URL: " + url);
return null;
}
return method.getResponseBodyAsStream();
} catch (final Exception ex) {
s_logger.error("Failed to read from URL: " + url);
return null;
}
}
public DiamondSDKManagerImpl(int connection_timeout, int require_timeout) throws IllegalArgumentException {
if (connection_timeout < 0)
throw new IllegalArgumentException("连接超时时间设置必须大于0[单位(毫秒)]!");
if (require_timeout < 0)
throw new IllegalArgumentException("请求超时时间设置必须大于0[单位(毫秒)]!");
this.connection_timeout = connection_timeout;
this.require_timeout = require_timeout;
int maxHostConnections = 50;
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxHostConnections);
connectionManager.getParams().setStaleCheckingEnabled(true);
this.client = new HttpClient(connectionManager);
// 设置连接超时时间
client.getHttpConnectionManager().getParams().setConnectionTimeout(this.connection_timeout);
// 设置读超时为1分钟
client.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);
client.getParams().setContentCharset("GBK");
log.info("设置连接超时时间为: " + this.connection_timeout + "毫秒");
}
protected void initHttpClient() {
if (MockServer.isTestMode()) {
return;
}
HostConfiguration hostConfiguration = new HostConfiguration();
hostConfiguration.setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
diamondConfigure.getPort());
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.closeIdleConnections(diamondConfigure.getPollingIntervalTime() * 4000);
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
params.setStaleCheckingEnabled(diamondConfigure.isConnectionStaleCheckingEnabled());
params.setMaxConnectionsPerHost(hostConfiguration, diamondConfigure.getMaxHostConnections());
params.setMaxTotalConnections(diamondConfigure.getMaxTotalConnections());
params.setConnectionTimeout(diamondConfigure.getConnectionTimeout());
// 设置读超时为1分钟,
// [email protected]
params.setSoTimeout(60 * 1000);
connectionManager.setParams(params);
httpClient = new HttpClient(connectionManager);
httpClient.setHostConfiguration(hostConfiguration);
}
@Bean
public SAMLProcessorImpl processor() {
HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
ArtifactResolutionProfileImpl artifactResolutionProfile = new ArtifactResolutionProfileImpl(httpClient);
HTTPSOAP11Binding soapBinding = new HTTPSOAP11Binding(parserPool());
artifactResolutionProfile.setProcessor(new SAMLProcessorImpl(soapBinding));
VelocityEngine velocityEngine = VelocityFactory.getEngine();
Collection<SAMLBinding> bindings = new ArrayList<>();
bindings.add(new HTTPRedirectDeflateBinding(parserPool()));
bindings.add(new HTTPPostBinding(parserPool(), velocityEngine));
bindings.add(new HTTPArtifactBinding(parserPool(), velocityEngine, artifactResolutionProfile));
bindings.add(new HTTPSOAP11Binding(parserPool()));
bindings.add(new HTTPPAOS11Binding(parserPool()));
return new SAMLProcessorImpl(bindings);
}
/**
* Gets the maximum number of connections to be used for a particular host config. If
* the value has not been specified for the given host the default value will be
* returned.
*
* @param hostConfiguration The host config.
* @return The maximum number of connections to be used for the given host config.
*
* @see #MAX_HOST_CONNECTIONS
*/
public int getMaxConnectionsPerHost(HostConfiguration hostConfiguration) {
Map m = (Map) getParameter(MAX_HOST_CONNECTIONS);
if (m == null) {
// MAX_HOST_CONNECTIONS have not been configured, using the default value
return MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS;
} else {
Integer max = (Integer) m.get(hostConfiguration);
if (max == null && hostConfiguration != HostConfiguration.ANY_HOST_CONFIGURATION) {
// the value has not been configured specifically for this host config,
// use the default value
return getMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION);
} else {
return (
max == null
? MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS
: max.intValue()
);
}
}
}
private void createHttpClient() {
Protocol protocol = Protocol.getProtocol("https");
if (protocol == null) {
// ZAP: Dont override an existing protocol - it causes problems with ZAP
Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", easyhttps);
}
initialState = new HttpState();
MultiThreadedHttpConnectionManager connectionManager =
new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(1000);
connectionManager.getParams().setMaxTotalConnections(1000);
// connectionManager.set
httpclient = new HttpClient(connectionManager);
// httpclient.
}
private void initConfigurationContext() throws Exception {
HttpConnectionManager multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager();
HttpClient httpClient = new HttpClient(multiThreadedHttpConnectionManager);
File configFile = new File(DEFAULT_AXIS2_XML);
if (!configFile.exists()) {
configurationContext = ConfigurationContextFactory.createDefaultConfigurationContext();
configurationContext.setProperty(HTTPConstants.DEFAULT_MAX_CONNECTIONS_PER_HOST, MAX_CONNECTIONS_PER_HOST);
} else {
configurationContext = ConfigurationContextFactory.
createConfigurationContextFromFileSystem(DEFAULT_CLIENT_REPO, DEFAULT_AXIS2_XML);
}
configurationContext.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
configurationContext.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE);
Map<String, TransportOutDescription> transportsOut =
configurationContext.getAxisConfiguration().getTransportsOut();
for (TransportOutDescription transportOutDescription : transportsOut.values()) {
if (Constants.TRANSPORT_HTTP.equals(transportOutDescription.getName()) ||
Constants.TRANSPORT_HTTPS.equals(transportOutDescription.getName())) {
transportOutDescription.getSender().init(configurationContext, transportOutDescription);
}
}
}
/**
* A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs
*
* @param user
* can be NULL
* @param password
* can be NULL
* @return HttpClient
*/
public static HttpClient getHttpClientInstance(String user, String password) {
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionParams params = connectionManager.getParams();
// wait max 10 seconds to establish connection
params.setConnectionTimeout(10000);
// a read() call on the InputStream associated with this Socket
// will block for only this amount
params.setSoTimeout(10000);
HttpClient c = new HttpClient(connectionManager);
// use basic authentication if available
if (user != null && user.length() > 0) {
AuthScope authScope = new AuthScope(null, -1, null);
Credentials credentials = new UsernamePasswordCredentials(user, password);
c.getState().setCredentials(authScope, credentials);
}
return c;
}
/**
* A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs
*
* @param user
* can be NULL
* @param password
* can be NULL
* @return HttpClient
*/
public static HttpClient getHttpClientInstance(String user, String password) {
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionParams params = connectionManager.getParams();
// wait max 10 seconds to establish connection
params.setConnectionTimeout(10000);
// a read() call on the InputStream associated with this Socket
// will block for only this amount
params.setSoTimeout(10000);
HttpClient c = new HttpClient(connectionManager);
// use basic authentication if available
if (user != null && user.length() > 0) {
AuthScope authScope = new AuthScope(null, -1, null);
Credentials credentials = new UsernamePasswordCredentials(user, password);
c.getState().setCredentials(authScope, credentials);
}
return c;
}
public static InputStream getInputStreamFromUrl(String url, String user, String password) {
try {
Pair<String, Integer> hostAndPort = validateUrl(url);
HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
if ((user != null) && (password != null)) {
httpclient.getParams().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
}
// Execute the method.
GetMethod method = new GetMethod(url);
int statusCode = httpclient.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
s_logger.error("Failed to read from URL: " + url);
return null;
}
return method.getResponseBodyAsStream();
} catch (Exception ex) {
s_logger.error("Failed to read from URL: " + url);
return null;
}
}
private ConfigurationContext getClientConfigurationContext() throws AxisFault {
String clientRepositoryLocation = serverConfigurationService.getFirstProperty(CLIENT_REPOSITORY_LOCATION);
String clientAxis2XmlLocationn = serverConfigurationService.getFirstProperty(CLIENT_AXIS2_XML_LOCATION);
ConfigurationContext clientConfigContextToReturn = ConfigurationContextFactory
.createConfigurationContextFromFileSystem(clientRepositoryLocation, clientAxis2XmlLocationn);
MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
// Set the default max connections per host
int defaultMaxConnPerHost = 500;
Parameter defaultMaxConnPerHostParam = clientConfigContextToReturn.getAxisConfiguration()
.getParameter("defaultMaxConnPerHost");
if (defaultMaxConnPerHostParam != null) {
defaultMaxConnPerHost = Integer.parseInt((String) defaultMaxConnPerHostParam.getValue());
}
params.setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost);
// Set the max total connections
int maxTotalConnections = 15000;
Parameter maxTotalConnectionsParam = clientConfigContextToReturn.getAxisConfiguration()
.getParameter("maxTotalConnections");
if (maxTotalConnectionsParam != null) {
maxTotalConnections = Integer.parseInt((String) maxTotalConnectionsParam.getValue());
}
params.setMaxTotalConnections(maxTotalConnections);
params.setSoTimeout(600000);
params.setConnectionTimeout(600000);
httpConnectionManager.setParams(params);
clientConfigContextToReturn
.setProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER, httpConnectionManager);
clientConfigContextToReturn.setProperty(MicroIntegratorBaseConstants.WORK_DIR, serverWorkDir);
return clientConfigContextToReturn;
}
/**
* Method that initialize http client
*
* note: this method is used to export birt statistics files
* @param internalURL
* @return
* @throws MalformedURLException
*/
public static HttpClient initializeHttpClient(String internalURL) throws MalformedURLException {
HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
URL url = new URL(internalURL);
int port = (url.getPort() == -1) ? url.getDefaultPort() : url.getPort();
httpClient.getHostConfiguration()
.setHost(url.getHost(), port, url.getProtocol());
return httpClient;
}
/**
* 初始化HttpClient对象
*/
public static HttpClient getHttpClient() {
HttpClient client = new HttpClient();
// 设置Cookie处理策略,RFC_2109是支持较普遍的一个,还有其他cookie协议
client.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
// 设置超时时间
MultiThreadedHttpConnectionManager hcm = new MultiThreadedHttpConnectionManager();
hcm.getParams().setConnectionTimeout(HTTP_REQUEST_TIMEOUT);
client.setHttpConnectionManager(hcm);
return client;
}
public BitlyUrlShortenerImpl()
{
httpClient = new HttpClient();
httpClient.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
HostConfiguration hostConfiguration = new HostConfiguration();
hostConfiguration.setHost("api-ssl.bitly.com", 443, Protocol.getProtocol("https"));
httpClient.setHostConfiguration(hostConfiguration);
}
@Override
public void close()
{
if(httpClient != null)
{
HttpConnectionManager connectionManager = httpClient.getHttpConnectionManager();
if(connectionManager instanceof MultiThreadedHttpConnectionManager)
{
((MultiThreadedHttpConnectionManager)connectionManager).shutdown();
}
}
}
private HttpClient createHttpClient() {
//see http://hc.apache.org/httpclient-3.x/threading.html
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = connectionManager.getParams();
params.setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, PreferenceHelper.getInt(ServerConstants.HTTP_MAX_CONN_HOST_CONF_KEY, 50));
params.setMaxTotalConnections(PreferenceHelper.getInt(ServerConstants.HTTP_MAX_CONN_TOTAL_CONF_KEY, 150));
params.setConnectionTimeout(PreferenceHelper.getInt(ServerConstants.HTTP_CONN_TIMEOUT_CONF_KEY, 15000)); //15s
params.setSoTimeout(PreferenceHelper.getInt(ServerConstants.HTTP_SO_TIMEOUT_CONF_KEY, 30000)); //30s
connectionManager.setParams(params);
HttpClientParams clientParams = new HttpClientParams();
clientParams.setConnectionManagerTimeout(PreferenceHelper.getInt(ServerConstants.HTTP_CONN_MGR_TIMEOUT_CONF_KEY, 300000)); // 5 minutes
return new HttpClient(clientParams, connectionManager);
}
/**
* 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;
}
/**
* Shut down services that exist outside of the core.
*/
@Override
public void shutdown()
{
super.shutdown();
try
{
LOGGER.info("Shutting down Alfresco core container services");
AlfrescoSolrDataModel.getInstance().close();
SOLRAPIClientFactory.close();
MultiThreadedHttpConnectionManager.shutdownAll();
coreNames().forEach(trackerRegistry::removeTrackersForCore);
informationServers.clear();
if (!scheduler.isShutdown())
{
scheduler.pauseAll();
if (trackerRegistry.getModelTracker() != null)
trackerRegistry.getModelTracker().shutdown();
trackerRegistry.setModelTracker(null);
scheduler.shutdown();
}
}
catch (Exception exception)
{
LOGGER.error(
"Unable to properly shut down Alfresco core container services. See the exception below for further details.",
exception);
}
}
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 HttpProtocolHandler() {
// 创建一个线程安全的HTTP连接池
connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost);
connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn);
IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread();
ict.addConnectionManager(connectionManager);
ict.setConnectionTimeout(defaultIdleConnTimeout);
ict.start();
}
@VisibleForTesting
protected HTTPArtifactBinding createDefaultArtifactBinding(ServiceProviderBuilder builder) {
HttpClientParams params = new HttpClientParams();
params.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 60000);
HttpClient httpClient = new HttpClient(params, new MultiThreadedHttpConnectionManager());
ArtifactResolutionProfileImpl artifactResolutionProfile = new ArtifactResolutionProfileImpl(httpClient);
builder.setSharedObject(ArtifactResolutionProfile.class, artifactResolutionProfile);
HTTPSOAP11Binding soapBinding = new HTTPSOAP11Binding(parserPool);
artifactResolutionProfile.setProcessor(new SAMLProcessorImpl(soapBinding));
return new HTTPArtifactBinding(parserPool, getVelocityEngine(), artifactResolutionProfile);
}
static void shutdown(@NotNull final HttpClient... httpClients) {
for (final HttpClient httpClient : httpClients) {
if (httpClient.getHttpConnectionManager() instanceof MultiThreadedHttpConnectionManager) {
try {
((MultiThreadedHttpConnectionManager)httpClient.getHttpConnectionManager()).shutdown();
} catch (Exception e) {
LOG.debug("Got exception while shutting down httpClient " + httpClient + ".", e);
}
}
}
}
public static void checkUrlExistence(final String url) {
if (url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https")) {
final HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
final HeadMethod httphead = new HeadMethod(url);
try {
if (httpClient.executeMethod(httphead) != HttpStatus.SC_OK) {
throw new IllegalArgumentException("Invalid URL: " + url);
}
} catch (final HttpException hte) {
throw new IllegalArgumentException("Cannot reach URL: " + url);
} catch (final IOException ioe) {
throw new IllegalArgumentException("Cannot reach URL: " + url);
}
}
}
/**
* 私有的构造方法
*/
private HttpProtocolHandler() {
// 创建一个线程安全的HTTP连接池
connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost);
connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn);
IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread();
ict.addConnectionManager(connectionManager);
ict.setConnectionTimeout(defaultIdleConnTimeout);
ict.start();
}