use of org.apache.hc.core5.http.io.SocketConfig in project httpcomponents-core by apache.
the class ClassicTestServer method start.
public void start(final Http1Config http1Config, final HttpProcessor httpProcessor, final Decorator<HttpServerRequestHandler> handlerDecorator) throws IOException {
if (serverRef.get() == null) {
final HttpServerRequestHandler handler = new BasicHttpServerRequestHandler(registry);
final HttpService httpService = new HttpService(httpProcessor != null ? httpProcessor : HttpProcessors.server(), handlerDecorator != null ? handlerDecorator.decorate(handler) : new BasicHttpServerExpectationDecorator(handler), DefaultConnectionReuseStrategy.INSTANCE, LoggingHttp1StreamListener.INSTANCE);
final HttpServer server = new HttpServer(0, httpService, null, socketConfig, sslContext != null ? sslContext.getServerSocketFactory() : ServerSocketFactory.getDefault(), new LoggingBHttpServerConnectionFactory(sslContext != null ? URIScheme.HTTPS.id : URIScheme.HTTP.id, http1Config != null ? http1Config : Http1Config.DEFAULT, CharCodingConfig.DEFAULT), null, LoggingExceptionListener.INSTANCE);
if (serverRef.compareAndSet(null, server)) {
server.start();
}
} else {
throw new IllegalStateException("Server already running");
}
}
use of org.apache.hc.core5.http.io.SocketConfig in project httpcomponents-core by apache.
the class RequesterBootstrap method create.
public HttpRequester create() {
final HttpRequestExecutor requestExecutor = new HttpRequestExecutor(HttpRequestExecutor.DEFAULT_WAIT_FOR_CONTINUE, connReuseStrategy != null ? connReuseStrategy : DefaultConnectionReuseStrategy.INSTANCE, streamListener);
final ManagedConnPool<HttpHost, HttpClientConnection> connPool;
switch(poolConcurrencyPolicy != null ? poolConcurrencyPolicy : PoolConcurrencyPolicy.STRICT) {
case LAX:
connPool = new LaxConnPool<>(defaultMaxPerRoute > 0 ? defaultMaxPerRoute : 20, timeToLive, poolReusePolicy, new DefaultDisposalCallback<>(), connPoolListener);
break;
case STRICT:
default:
connPool = new StrictConnPool<>(defaultMaxPerRoute > 0 ? defaultMaxPerRoute : 20, maxTotal > 0 ? maxTotal : 50, timeToLive, poolReusePolicy, new DefaultDisposalCallback<>(), connPoolListener);
break;
}
return new HttpRequester(requestExecutor, httpProcessor != null ? httpProcessor : HttpProcessors.client(), connPool, socketConfig != null ? socketConfig : SocketConfig.DEFAULT, connectFactory != null ? connectFactory : new DefaultBHttpClientConnectionFactory(Http1Config.DEFAULT, CharCodingConfig.DEFAULT), sslSocketFactory, sslSetupHandler != null ? sslSetupHandler : new DefaultTlsSetupHandler(), sslSessionVerifier, DefaultAddressResolver.INSTANCE);
}
use of org.apache.hc.core5.http.io.SocketConfig in project httpcomponents-core by apache.
the class ClassicServerFilterExample method main.
public static void main(final String[] args) throws Exception {
int port = 8080;
if (args.length >= 1) {
port = Integer.parseInt(args[0]);
}
final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
final HttpServer server = ServerBootstrap.bootstrap().setListenerPort(port).setSocketConfig(socketConfig).replaceFilter(StandardFilter.EXPECT_CONTINUE.name(), new AbstractHttpServerAuthFilter<String>(false) {
@Override
protected String parseChallengeResponse(final String authorizationValue, final HttpContext context) throws HttpException {
return authorizationValue;
}
@Override
protected boolean authenticate(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
return "let me pass".equals(challengeResponse);
}
@Override
protected String generateChallenge(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
return "who goes there?";
}
}).addFilterFirst("my-filter", (request, responseTrigger, context, chain) -> {
if (request.getRequestUri().equals("/back-door")) {
final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_OK);
response.setEntity(new StringEntity("Welcome", ContentType.TEXT_PLAIN));
responseTrigger.submitResponse(response);
} else {
chain.proceed(request, new HttpFilterChain.ResponseTrigger() {
@Override
public void sendInformation(final ClassicHttpResponse response) throws HttpException, IOException {
responseTrigger.sendInformation(response);
}
@Override
public void submitResponse(final ClassicHttpResponse response) throws HttpException, IOException {
response.addHeader("X-Filter", "My-Filter");
responseTrigger.submitResponse(response);
}
}, context);
}
}).register("*", (request, response, context) -> {
// do something useful
response.setCode(HttpStatus.SC_OK);
response.setEntity(new StringEntity("Hello"));
}).create();
server.start();
Runtime.getRuntime().addShutdownHook(new Thread(() -> server.close(CloseMode.GRACEFUL)));
System.out.println("Listening on port " + port);
server.awaitTermination(TimeValue.MAX_VALUE);
}
use of org.apache.hc.core5.http.io.SocketConfig in project commons-vfs by apache.
the class Http5FileProvider method createConnectionManager.
private HttpClientConnectionManager createConnectionManager(final Http5FileSystemConfigBuilder builder, final FileSystemOptions fileSystemOptions) throws FileSystemException {
final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(Timeout.ofMilliseconds(builder.getSoTimeoutDuration(fileSystemOptions).toMillis())).build();
final String[] tlsVersions = builder.getTlsVersions(fileSystemOptions).split("\\s*,\\s*");
final TLS[] tlsArray = Stream.of(tlsVersions).map(TLS::valueOf).toArray(TLS[]::new);
final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create().setSslContext(createSSLContext(builder, fileSystemOptions)).setHostnameVerifier(createHostnameVerifier(builder, fileSystemOptions)).setTlsVersions(tlsArray).build();
return PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).setMaxConnTotal(builder.getMaxTotalConnections(fileSystemOptions)).setMaxConnPerRoute(builder.getMaxConnectionsPerHost(fileSystemOptions)).setDefaultSocketConfig(socketConfig).build();
}
use of org.apache.hc.core5.http.io.SocketConfig in project mercury by yellow013.
the class ClientConfiguration method main.
public static final void main(final String[] args) throws Exception {
// Use custom message parser / writer to customize the way HTTP
// messages are parsed from and written out to the data stream.
final HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {
@Override
public HttpMessageParser<ClassicHttpResponse> create(final Http1Config h1Config) {
final LineParser lineParser = new BasicLineParser() {
@Override
public Header parseHeader(final CharArrayBuffer buffer) {
try {
return super.parseHeader(buffer);
} catch (final ParseException ex) {
return new BasicHeader(buffer.toString(), null);
}
}
};
return new DefaultHttpResponseParser(lineParser, DefaultClassicHttpResponseFactory.INSTANCE, h1Config);
}
};
final HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();
// Create HTTP/1.1 protocol configuration
final Http1Config h1Config = Http1Config.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build();
// Create connection configuration
final CharCodingConfig connectionConfig = CharCodingConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(StandardCharsets.UTF_8).build();
// Use a custom connection factory to customize the process of
// initialization of outgoing HTTP connections. Beside standard connection
// configuration parameters HTTP connection factory can define message
// parser / writer routines to be employed by individual connections.
@SuppressWarnings("unused") final HttpConnectionFactory<ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(h1Config, connectionConfig, requestWriterFactory, responseParserFactory);
// Client HTTP connection objects when fully initialized can be bound to
// an arbitrary network socket. The process of network socket initialization,
// its connection to a remote address and binding to a local one is controlled
// by a connection socket factory.
// SSL context for secure connections can be created either based on
// system or application specific properties.
final SSLContext sslcontext = SSLContexts.createSystemDefault();
// Create a registry of custom connection socket factories for supported
// protocol schemes.
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext)).build();
// Use custom DNS resolver to override the system DNS resolution.
final DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
@Override
public InetAddress[] resolve(final String host) throws UnknownHostException {
if (host.equalsIgnoreCase("myhost")) {
return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
} else {
return super.resolve(host);
}
}
};
// Create a connection manager with custom configuration.
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, PoolConcurrencyPolicy.STRICT, PoolReusePolicy.LIFO, TimeValue.ofMinutes(5), null, dnsResolver, null);
// Create socket configuration
final SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
// Configure the connection manager to use socket configuration either
// by default or for a specific host.
connManager.setDefaultSocketConfig(socketConfig);
// Validate connections after 1 sec of inactivity
connManager.setValidateAfterInactivity(TimeValue.ofSeconds(10));
// Configure total max or per route limits for persistent connections
// that can be kept in the pool or leased by the connection manager.
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(10);
connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);
// Use custom cookie store if necessary.
final CookieStore cookieStore = new BasicCookieStore();
// Use custom credentials provider if necessary.
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// Create global request configuration
final RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(StandardCookieSpec.STRICT).setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(StandardAuthScheme.NTLM, StandardAuthScheme.DIGEST)).setProxyPreferredAuthSchemes(Collections.singletonList(StandardAuthScheme.BASIC)).build();
try (final CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credentialsProvider).setProxy(new HttpHost("myproxy", 8080)).setDefaultRequestConfig(defaultRequestConfig).build()) {
final HttpGet httpget = new HttpGet("http://httpbin.org/get");
// Request configuration can be overridden at the request level.
// They will take precedence over the one set at the client level.
final RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setConnectionRequestTimeout(Timeout.ofSeconds(5)).setConnectTimeout(Timeout.ofSeconds(5)).setProxy(new HttpHost("myotherproxy", 8080)).build();
httpget.setConfig(requestConfig);
// Execution context can be customized locally.
final HttpClientContext context = HttpClientContext.create();
// Contextual attributes set the local context level will take
// precedence over those set at the client level.
context.setCookieStore(cookieStore);
context.setCredentialsProvider(credentialsProvider);
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (final CloseableHttpResponse response = httpclient.execute(httpget, context)) {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
// Once the request has been executed the local context can
// be used to examine updated state and various objects affected
// by the request execution.
// Last executed request
context.getRequest();
// Execution route
context.getHttpRoute();
// Auth exchanges
context.getAuthExchanges();
// Cookie origin
context.getCookieOrigin();
// Cookie spec used
context.getCookieSpec();
// User security token
context.getUserToken();
}
}
}
Aggregations