下面列出了org.apache.http.conn.scheme.SchemeRegistry#register ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public HttpClient getHttpsClientTrustAll() {
try {
SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy(){
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}, new AllowAllHostnameVerifier());
PlainSocketFactory psf = PlainSocketFactory.getSocketFactory();
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", 80, psf));
registry.register(new Scheme("https", 443, sf));
ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
return new DefaultHttpClient(ccm);
} catch (Exception ex) {
log.error("Failed to create TrustAll https client", ex);
return new DefaultHttpClient();
}
}
/**
* Replicates {@link ApacheHttpTransport#newDefaultHttpClient()} with one exception:
*
* 1 retry is allowed.
*
* @see DefaultHttpRequestRetryHandler
*/
DefaultHttpClient newDefaultHttpClient(
SSLSocketFactory socketFactory, HttpParams params, ProxySelector proxySelector) {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", socketFactory, 443));
ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);
DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager, params);
// retry only once
defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(1, true));
if (proxySelector != null) {
defaultHttpClient.setRoutePlanner(new ProxySelectorRoutePlanner(registry, proxySelector));
}
defaultHttpClient.setKeepAliveStrategy((response, context) -> KEEP_ALIVE_DURATION);
return defaultHttpClient;
}
public HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(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();
}
}
@Override
public DefaultHttpClient create(final HttpMethod method, final URI uri) {
final TrustStrategy acceptTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(final X509Certificate[] certificate, final String authType) {
return true;
}
};
final SchemeRegistry registry = new SchemeRegistry();
try {
final SSLSocketFactory ssf =
new SSLSocketFactory(acceptTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registry.register(new Scheme(uri.getScheme(), uri.getPort(), ssf));
} catch (Exception e) {
throw new ODataRuntimeException(e);
}
final DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(registry));
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);
return httpClient;
}
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);
}
/**
* 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();
}
}
/**
* 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();
}
}
@Override
public HttpClient produce(InputStream keystore, String keypass) {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(keystore, keypass.toCharArray());
SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = basicParams();
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();
}
}
public void setSSLContext(final SSLContext sslContext) {
SchemeRegistry registry = getConnectionManager().getSchemeRegistry();
registry.unregister("https");
if (DefaultServer.getHostAddress(DefaultServer.DEFAULT).equals("localhost")) {
registry.register(new Scheme("https", 443, new SSLSocketFactory(sslContext)));
registry.register(new Scheme("https", DefaultServer.getHostSSLPort("default"), new SSLSocketFactory(sslContext)));
} else {
registry.register(new Scheme("https", 443, new SSLSocketFactory(sslContext, NO_OP_VERIFIER)));
registry.register(new Scheme("https", DefaultServer.getHostSSLPort("default"), new SSLSocketFactory(sslContext, NO_OP_VERIFIER)));
}
}
/**
* Returns default instance of SchemeRegistry
*
* @param fixNoHttpResponseException Whether to fix issue or not, by omitting SSL verification
* @param httpPort HTTP port to be used, must be greater than 0
* @param httpsPort HTTPS port to be used, must be greater than 0
*/
private static SchemeRegistry getDefaultSchemeRegistry(boolean fixNoHttpResponseException, int httpPort, int httpsPort) {
if (fixNoHttpResponseException) {
Log.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates.");
}
if (httpPort < 1) {
httpPort = 80;
Log.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80");
}
if (httpsPort < 1) {
httpsPort = 443;
Log.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443");
}
// Fix to SSL flaw in API < ICS
// See https://code.google.com/p/android/issues/detail?id=13117
SSLSocketFactory sslSocketFactory;
if (fixNoHttpResponseException) {
sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory();
} else {
sslSocketFactory = SSLSocketFactory.getSocketFactory();
}
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort));
schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort));
return schemeRegistry;
}
private HttpClient getHttpClient() {
if (this._httpClient == null) {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpConnectionParams.setConnectionTimeout(params, 300000);
HttpConnectionParams.setSoTimeout(params, 300000);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
params, schReg);
this._httpClient = new DefaultHttpClient(conMgr, params);
if (this._cookieStore != null) {
DefaultHttpClient dhttpclient = (DefaultHttpClient) this._httpClient;
dhttpclient.setCookieStore(this._cookieStore);
}
}
return this._httpClient;
}
public DefaultHttpClient createHttpClient() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme(IDataSource.SCHEME_HTTP_TAG, PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme(IDataSource.SCHEME_HTTPS_TAG, SSLSocketFactory.getSocketFactory(), 443));
HttpParams params = createHttpParams();
return new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);
}
/**
* Returns default instance of SchemeRegistry
*
* @param fixNoHttpResponseException Whether to fix or not issue, by ommiting SSL verification
* @param httpPort HTTP port to be used, must be greater than 0
* @param httpsPort HTTPS port to be used, must be greater than 0
*/
private static SchemeRegistry getDefaultSchemeRegistry(boolean fixNoHttpResponseException, int httpPort, int httpsPort) {
if (fixNoHttpResponseException) {
Log.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates.");
}
if (httpPort < 1) {
httpPort = 80;
Log.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80");
}
if (httpsPort < 1) {
httpsPort = 443;
Log.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443");
}
// Fix to SSL flaw in API < ICS
// See https://code.google.com/p/android/issues/detail?id=13117
SSLSocketFactory sslSocketFactory;
if (fixNoHttpResponseException)
sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory();
else
sslSocketFactory = SSLSocketFactory.getSocketFactory();
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort));
schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort));
return schemeRegistry;
}
public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException {
this.configuration = configuration;
HttpProtocolParams.setContentCharset(globalParams, getConfiguration().getContentCharset());
HttpProtocolParams.setUseExpectContinue(globalParams, false);
// These are some safety settings, we should never run into these timeouts as we
// do our own expiration checking
HttpConnectionParams.setConnectionTimeout(globalParams, (getConfiguration().getTimeoutSeconds()+5) * 1000);
HttpConnectionParams.setSoTimeout(globalParams, (getConfiguration().getTimeoutSeconds()+5) * 1000);
HttpConnectionParams.setStaleCheckingEnabled(globalParams, getConfiguration().getStaleCheckingEnabled());
if (getConfiguration().getSocketBufferSize() != -1)
HttpConnectionParams.setSocketBufferSize(globalParams, getConfiguration().getSocketBufferSize());
// Only register 80, not 443 and SSL
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
clientConnectionManager = new PoolingClientConnectionManager(registry);
clientConnectionManager.setMaxTotal(getConfiguration().getMaxTotalConnections());
clientConnectionManager.setDefaultMaxPerRoute(getConfiguration().getMaxTotalPerRoute());
httpClient = new DefaultHttpClient(clientConnectionManager, globalParams);
if (getConfiguration().getRequestRetryCount() != -1) {
httpClient.setHttpRequestRetryHandler(
new DefaultHttpRequestRetryHandler(getConfiguration().getRequestRetryCount(), false)
);
}
}
public 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);
HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
HttpConnectionParams.setSoTimeout(params, 5 * 1000);
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();
}
}
@Override
public HttpClient produce() {
//Set up your HTTPS connection
SchemeRegistry schemeRegistry = new SchemeRegistry();
// http scheme
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// https scheme
schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
HttpParams params = basicParams();
ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
return new DefaultHttpClient(cm, params);
}
/**
* Returns default instance of SchemeRegistry
*
* @param fixNoHttpResponseException Whether to fix issue or not, by omitting SSL verification
* @param httpPort HTTP port to be used, must be greater than 0
* @param httpsPort HTTPS port to be used, must be greater than 0
*/
private static SchemeRegistry getDefaultSchemeRegistry(boolean fixNoHttpResponseException, int httpPort, int httpsPort) {
if (fixNoHttpResponseException) {
Log.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates.");
}
if (httpPort < 1) {
httpPort = 80;
Log.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80");
}
if (httpsPort < 1) {
httpsPort = 443;
Log.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443");
}
// Fix to SSL flaw in API < ICS
// See https://code.google.com/p/android/issues/detail?id=13117
SSLSocketFactory sslSocketFactory;
if (fixNoHttpResponseException) {
sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory();
} else {
sslSocketFactory = SSLSocketFactory.getSocketFactory();
}
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort));
schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort));
return schemeRegistry;
}
private static SchemeRegistry prepareSchemeRegistry() {
SchemeRegistry sr = new SchemeRegistry();
Scheme http = new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80);
sr.register(http);
Scheme https = new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443);
sr.register(https);
return sr;
}
public 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);
HttpProtocolParams.setUserAgent(params, HttpHeader.getUA());
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);
DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
httpClient.setCookieStore(new BasicCookieStore());
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 25000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 25000);
return httpClient;
} catch (Exception e) {
return new DefaultHttpClient();
}
}
public void test() throws Exception {
exe = Executors.newFixedThreadPool(POOL_SIZE);
HttpParams params =new BasicHttpParams();
/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(params, 1000);
/* 连接超时 */
HttpConnectionParams.setConnectionTimeout(params, 2000);
/* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 4000);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
//ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
PoolingClientConnectionManager cm=new PoolingClientConnectionManager(schemeRegistry);
cm.setMaxTotal(10);
final HttpClient httpClient = new DefaultHttpClient(cm,params);
// URIs to perform GETs on
final String[] urisToGet = urls;
/* 有多少url创建多少线程,url多时机子撑不住
// create a thread for each URI
GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i < threads.length; i++) {
HttpGet httpget = new HttpGet(urisToGet[i]);
threads[i] = new GetThread(httpClient, httpget);
}
// start the threads
for (int j = 0; j < threads.length; j++) {
threads[j].start();
}
// join the threads,等待所有请求完成
for (int j = 0; j < threads.length; j++) {
threads[j].join();
}
使用线程池*/
for (int i = 0; i < urisToGet.length; i++) {
final int j=i;
System.out.println(j);
HttpGet httpget = new HttpGet(urisToGet[i]);
exe.execute( new GetThread(httpClient, httpget));
}
//创建线程池,每次调用POOL_SIZE
/*
for (int i = 0; i < urisToGet.length; i++) {
final int j=i;
System.out.println(j);
exe.execute(new Thread() {
@Override
public void run() {
this.setName("threadsPoolClient"+j);
try {
this.sleep(100);
System.out.println(j);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpGet httpget = new HttpGet(urisToGet[j]);
new GetThread(httpClient, httpget).get();
}
});
}
*/
//exe.shutdown();
System.out.println("Done");
}