本文整理汇总了Java中org.apache.http.config.SocketConfig类的典型用法代码示例。如果您正苦于以下问题:Java SocketConfig类的具体用法?Java SocketConfig怎么用?Java SocketConfig使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SocketConfig类属于org.apache.http.config包,在下文中一共展示了SocketConfig类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: afterPropertiesSet
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
@PostConstruct
public void afterPropertiesSet() throws Exception {
RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();
schemeRegistry.register("http", PlainConnectionSocketFactory.getSocketFactory());
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(new KeyManager[0], new TrustManager[]{new SimpleTrustManager()}, null);
SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslcontext);
schemeRegistry.register("https", sf);
pool = new PoolingHttpClientConnectionManager(schemeRegistry.build());
pool.setMaxTotal(maxConnection);
pool.setDefaultMaxPerRoute(maxConnection);
pool.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(sotimeout).build());
}
示例2: DefaultConnector
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
/**
*
*/
public DefaultConnector() {
final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.closeIdleConnections(120, TimeUnit.SECONDS);
// would be nice to set this from outside -> keep alive
final SocketConfig sConfig = SocketConfig.custom().setSoKeepAlive(true).setSoTimeout(Context.SOCKET_TO).build();
cm.setDefaultSocketConfig(sConfig);
cm.setMaxTotal(150);
cm.setDefaultMaxPerRoute(150);
cm.setValidateAfterInactivity(0);
final HttpRequestRetryHandler rh = new DefaultHttpRequestRetryHandler(3, true);
httpClient = HttpClients.custom().setRetryHandler(rh).setConnectionManager(cm).build();
}
示例3: createCommonsHttpRestTemplate
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
public static RestOperations createCommonsHttpRestTemplate(int maxConnPerRoute, int maxConnTotal,
int connectTimeout, int soTimeout, int retryTimes, RetryPolicyFactory retryPolicyFactory) {
HttpClient httpClient = HttpClientBuilder.create()
.setMaxConnPerRoute(maxConnPerRoute)
.setMaxConnTotal(maxConnTotal)
.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(soTimeout).build())
.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(connectTimeout).build())
.build();
ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
//set jackson mapper
for (HttpMessageConverter<?> hmc : restTemplate.getMessageConverters()) {
if (hmc instanceof MappingJackson2HttpMessageConverter) {
ObjectMapper objectMapper = createObjectMapper();
MappingJackson2HttpMessageConverter mj2hmc = (MappingJackson2HttpMessageConverter) hmc;
mj2hmc.setObjectMapper(objectMapper);
}
}
return (RestOperations) Proxy.newProxyInstance(RestOperations.class.getClassLoader(),
new Class[]{RestOperations.class},
new RetryableRestOperationsHandler(restTemplate, retryTimes, retryPolicyFactory));
}
示例4: HttpFederationClient
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
public HttpFederationClient(HomeserverState global, FederationDomainResolver resolver) {
this.global = global;
this.resolver = resolver;
try {
SocketConfig sockConf = SocketConfig.custom().setSoTimeout(30000).build();
// FIXME properly handle SSL context by validating certificate hostname
SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustAllStrategy()).build();
HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
this.client = HttpClientBuilder.create()
.disableAuthCaching()
.disableAutomaticRetries()
.disableCookieManagement()
.disableRedirectHandling()
.setDefaultSocketConfig(sockConf)
.setSSLSocketFactory(sslSocketFactory)
.setUserAgent(global.getAppName() + "/" + global.getAppVersion())
.build();
} catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException(e);
}
}
示例5: gen
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
@Override
public CrawlerHttpClient gen(CrawlerHttpClientBuilder proxyFeedBackDecorateHttpClientBuilder) {
SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setSoLinger(-1).setSoReuseAddress(false)
.setSoTimeout(ProxyConstant.SOCKETSO_TIMEOUT).setTcpNoDelay(true).build();
return proxyFeedBackDecorateHttpClientBuilder
.setDefaultSocketConfig(socketConfig)
// .setSSLSocketFactory(sslConnectionSocketFactory)
// dungproxy0.0.6之后的版本,默认忽略https证书检查
.setRedirectStrategy(new LaxRedirectStrategy())
//注意,这里使用ua生产算法自动产生ua,如果是mobile,可以使用
// com.virjar.vscrawler.core.net.useragent.UserAgentBuilder.randomAppUserAgent()
.setUserAgent(UserAgentBuilder.randomUserAgent())
//对于爬虫来说,连接池没啥卵用,直接禁止掉(因为我们可能创建大量HttpClient,每个HttpClient一个连接池,会把系统socket资源撑爆)
//测试开80个httpClient抓数据大概一个小时系统就会宕机
.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
.build();
}
示例6: getHttpClient
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
public static CloseableHttpClient getHttpClient(HttpClientConnectionManager connectionManager, int maxConnections) {
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();
ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build();
SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true)
.setSoReuseAddress(true).build();
String userAgent = MessageFormat
.format("MyCoRe/{0} ({1}; java {2})", MCRCoreVersion.getCompleteVersion(), MCRConfiguration.instance()
.getString("MCR.NameOfProject", "undefined"), System.getProperty("java.version"));
//setup http client
return HttpClients.custom().setConnectionManager(connectionManager)
.setUserAgent(userAgent).setRetryHandler(new MCRRetryHandler(maxConnections))
.setDefaultRequestConfig(requestConfig).setDefaultConnectionConfig(connectionConfig)
.setDefaultSocketConfig(socketConfig).build();
}
示例7: HttpRestClient
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
public HttpRestClient(String user, String password) {
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(DEFAULT_SOCKET_TIMEOUT * 1000).build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(DEFAULT_REQUEST_TIMEOUT * 1000)
.setSocketTimeout(DEFAULT_SOCKET_TIMEOUT * 1000)
.setConnectionRequestTimeout(DEFAULT_REQUEST_TIMEOUT * 1000).build();
httpConnectionManager.setMaxTotal(DEFAULT_CONN_NUM);
httpConnectionManager.setDefaultMaxPerRoute(DEFAULT_CONN_NUM);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(user, password));
client = HttpClients.custom().setConnectionManager(httpConnectionManager)
.setDefaultRequestConfig(requestConfig)
.setDefaultSocketConfig(socketConfig)
.setDefaultCredentialsProvider(credsProvider).build();
}
示例8: getClient
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
@NotNull
private HttpClient getClient(@NotNull SVNURL repositoryUrl) {
// TODO: Implement algorithm of resolving necessary enabled protocols (TLSv1 vs SSLv3) instead of just using values from Settings.
SSLContext sslContext = createSslContext(repositoryUrl);
List<String> supportedProtocols = getSupportedSslProtocols();
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, ArrayUtil.toStringArray(supportedProtocols), null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
// TODO: Seems more suitable here to read timeout values directly from config file - without utilizing SvnAuthenticationManager.
final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
if (haveDataForTmpConfig()) {
IdeHttpClientHelpers.ApacheHttpClient4.setProxyIfEnabled(requestConfigBuilder);
IdeHttpClientHelpers.ApacheHttpClient4.setProxyCredentialsIfEnabled(credentialsProvider);
}
return HttpClients.custom()
.setSSLSocketFactory(socketFactory)
.setDefaultSocketConfig(SocketConfig.custom()
.setSoTimeout(getAuthenticationManager().getReadTimeout(repositoryUrl))
.build())
.setDefaultRequestConfig(requestConfigBuilder
.setConnectTimeout(getAuthenticationManager().getConnectTimeout(repositoryUrl))
.build())
.setDefaultCredentialsProvider(credentialsProvider)
.build();
}
示例9: setUp
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
final SocketConfig socketConfig = SocketConfig.custom()
.setSoTimeout(15000)
.build();
this.serverBootstrap = ServerBootstrap.bootstrap()
.setSocketConfig(socketConfig)
.setServerInfo(ORIGIN)
.registerHandler("/echo/*", new EchoHandler())
.registerHandler("/random/*", new RandomHandler());
if (this.scheme.equals(ProtocolScheme.https)) {
this.serverBootstrap.setSslContext(SSLTestContexts.createServerSSLContext());
}
this.connManager = new PoolingHttpClientConnectionManager();
this.clientBuilder = HttpClientBuilder.create()
.setDefaultSocketConfig(socketConfig)
.setConnectionManager(this.connManager);
}
示例10: testConnectTimeout
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
@Test(expected=ConnectTimeoutException.class)
public void testConnectTimeout() throws Exception {
final HttpContext context = new BasicHttpContext();
final HttpHost host = new HttpHost("somehost");
final InetAddress ip1 = InetAddress.getByAddress(new byte[] {10, 0, 0, 1});
final InetAddress ip2 = InetAddress.getByAddress(new byte[] {10, 0, 0, 2});
Mockito.when(dnsResolver.resolve("somehost")).thenReturn(new InetAddress[] { ip1, ip2 });
Mockito.when(socketFactoryRegistry.lookup("http")).thenReturn(plainSocketFactory);
Mockito.when(schemePortResolver.resolve(host)).thenReturn(80);
Mockito.when(plainSocketFactory.createSocket(Mockito.<HttpContext>any())).thenReturn(socket);
Mockito.when(plainSocketFactory.connectSocket(
Mockito.anyInt(),
Mockito.<Socket>any(),
Mockito.<HttpHost>any(),
Mockito.<InetSocketAddress>any(),
Mockito.<InetSocketAddress>any(),
Mockito.<HttpContext>any())).thenThrow(new SocketTimeoutException());
connectionOperator.connect(conn, host, null, 1000, SocketConfig.DEFAULT, context);
}
示例11: testConnectFailure
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
@Test(expected=HttpHostConnectException.class)
public void testConnectFailure() throws Exception {
final HttpContext context = new BasicHttpContext();
final HttpHost host = new HttpHost("somehost");
final InetAddress ip1 = InetAddress.getByAddress(new byte[] {10, 0, 0, 1});
final InetAddress ip2 = InetAddress.getByAddress(new byte[] {10, 0, 0, 2});
Mockito.when(dnsResolver.resolve("somehost")).thenReturn(new InetAddress[] { ip1, ip2 });
Mockito.when(socketFactoryRegistry.lookup("http")).thenReturn(plainSocketFactory);
Mockito.when(schemePortResolver.resolve(host)).thenReturn(80);
Mockito.when(plainSocketFactory.createSocket(Mockito.<HttpContext>any())).thenReturn(socket);
Mockito.when(plainSocketFactory.connectSocket(
Mockito.anyInt(),
Mockito.<Socket>any(),
Mockito.<HttpHost>any(),
Mockito.<InetSocketAddress>any(),
Mockito.<InetSocketAddress>any(),
Mockito.<HttpContext>any())).thenThrow(new ConnectException());
connectionOperator.connect(conn, host, null, 1000, SocketConfig.DEFAULT, context);
}
示例12: getHttpClient
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
protected final CloseableHttpClient getHttpClient(final boolean useSpnego) throws Exception {
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
final HttpClientBuilder hcb = HttpClients.custom();
if (useSpnego) {
//SPNEGO/Kerberos setup
log.debug("SPNEGO activated");
final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);// new NegotiateSchemeProvider();
final Credentials jaasCreds = new JaasCredentials();
credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest",
"Guest"));
final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
.register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();
hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
}
hcb.setDefaultCredentialsProvider(credsProvider);
hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build());
final CloseableHttpClient httpClient = hcb.build();
return httpClient;
}
示例13: getHttpClient
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
protected HttpClient getHttpClient(Map<String, Object> options) throws GeneralSecurityException {
SocketConfig socketConfig = SocketConfig.custom()
.setSoKeepAlive(true).build();
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setDefaultSocketConfig(socketConfig);
httpClientBuilder.disableAuthCaching();
httpClientBuilder.disableAutomaticRetries();
if(options.containsKey("sslVerify") && !Boolean.parseBoolean(options.get("sslVerify").toString())) {
log.debug("Disabling all SSL certificate verification.");
SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
});
httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
httpClientBuilder.setSSLContext(sslContextBuilder.build());
}
return httpClientBuilder.build();
}
示例14: connect
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
@Override
public void connect(
final ManagedHttpClientConnection conn,
final HttpHost host,
final InetSocketAddress localAddress,
final int connectTimeout,
final SocketConfig socketConfig,
final HttpContext context) throws IOException {
try {
super.connect(conn, host, localAddress, connectTimeout, socketConfig, context);
}
catch (SSLProtocolException e) {
Boolean enableSniValue = (Boolean) context.getAttribute(SSLConnectionSocketFactoryImpl.ENABLE_SNI);
boolean enableSni = enableSniValue == null || enableSniValue;
if (enableSni && e.getMessage() != null && e.getMessage().equals("handshake alert: unrecognized_name")) {
//print.e("Server received saw wrong SNI host, retrying without SNI");
context.setAttribute(SSLConnectionSocketFactoryImpl.ENABLE_SNI, false);
super.connect(conn, host, localAddress, connectTimeout, socketConfig, context);
}
else throw e;
}
}
示例15: AbstractMigrateUsersToIncludeUsernames
import org.apache.http.config.SocketConfig; //导入依赖的package包/类
protected AbstractMigrateUsersToIncludeUsernames() {
final String host = System.getProperty(COMMUNITY_HOST);
final int port = Integer.parseInt(System.getProperty(COMMUNITY_PORT));
final AciServerDetails.TransportProtocol transportProtocol = AciServerDetails.TransportProtocol.valueOf(System.getProperty(COMMUNITY_PROTOCOL));
serverDetails = new AciServerDetails(transportProtocol, host, port);
processorFactory = new ProcessorFactoryImpl(new Jaxb2MarshallerFactory());
final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(HTTP_SOCKET_TIMEOUT).build();
final HttpClient httpClient = HttpClientBuilder.create()
.setMaxConnPerRoute(MAX_CONNECTIONS_PER_ROUTE)
.setMaxConnTotal(MAX_CONNECTIONS_TOTAL)
.setDefaultSocketConfig(socketConfig)
.build();
final AciHttpClient aciHttpClient = new AciHttpClientImpl(httpClient);
aciService = new AciServiceImpl(aciHttpClient, serverDetails);
}