Search in sources :

Example 1 with SocketConfig

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");
    }
}
Also used : BasicHttpServerExpectationDecorator(org.apache.hc.core5.http.io.support.BasicHttpServerExpectationDecorator) HttpServerRequestHandler(org.apache.hc.core5.http.io.HttpServerRequestHandler) BasicHttpServerRequestHandler(org.apache.hc.core5.http.io.support.BasicHttpServerRequestHandler) HttpService(org.apache.hc.core5.http.impl.io.HttpService) HttpServer(org.apache.hc.core5.http.impl.bootstrap.HttpServer) BasicHttpServerRequestHandler(org.apache.hc.core5.http.io.support.BasicHttpServerRequestHandler)

Example 2 with SocketConfig

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);
}
Also used : HttpRequestExecutor(org.apache.hc.core5.http.impl.io.HttpRequestExecutor) DefaultDisposalCallback(org.apache.hc.core5.pool.DefaultDisposalCallback) HttpHost(org.apache.hc.core5.http.HttpHost) HttpClientConnection(org.apache.hc.core5.http.io.HttpClientConnection) DefaultBHttpClientConnectionFactory(org.apache.hc.core5.http.impl.io.DefaultBHttpClientConnectionFactory) DefaultTlsSetupHandler(org.apache.hc.core5.http.io.ssl.DefaultTlsSetupHandler)

Example 3 with SocketConfig

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);
}
Also used : BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpException(org.apache.hc.core5.http.HttpException) TimeValue(org.apache.hc.core5.util.TimeValue) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) IOException(java.io.IOException) SocketConfig(org.apache.hc.core5.http.io.SocketConfig) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) TimeUnit(java.util.concurrent.TimeUnit) HttpServer(org.apache.hc.core5.http.impl.bootstrap.HttpServer) AbstractHttpServerAuthFilter(org.apache.hc.core5.http.io.support.AbstractHttpServerAuthFilter) URIAuthority(org.apache.hc.core5.net.URIAuthority) ServerBootstrap(org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap) ContentType(org.apache.hc.core5.http.ContentType) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpFilterChain(org.apache.hc.core5.http.io.HttpFilterChain) CloseMode(org.apache.hc.core5.io.CloseMode) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) HttpStatus(org.apache.hc.core5.http.HttpStatus) StandardFilter(org.apache.hc.core5.http.impl.bootstrap.StandardFilter) URIAuthority(org.apache.hc.core5.net.URIAuthority) SocketConfig(org.apache.hc.core5.http.io.SocketConfig) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) IOException(java.io.IOException) AbstractHttpServerAuthFilter(org.apache.hc.core5.http.io.support.AbstractHttpServerAuthFilter) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) HttpServer(org.apache.hc.core5.http.impl.bootstrap.HttpServer) HttpException(org.apache.hc.core5.http.HttpException) HttpFilterChain(org.apache.hc.core5.http.io.HttpFilterChain) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse)

Example 4 with SocketConfig

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();
}
Also used : SocketConfig(org.apache.hc.core5.http.io.SocketConfig) TLS(org.apache.hc.core5.http.ssl.TLS) SSLConnectionSocketFactory(org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory)

Example 5 with SocketConfig

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();
        }
    }
}
Also used : CharCodingConfig(org.apache.hc.core5.http.config.CharCodingConfig) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) CharArrayBuffer(org.apache.hc.core5.util.CharArrayBuffer) SystemDefaultDnsResolver(org.apache.hc.client5.http.SystemDefaultDnsResolver) SSLConnectionSocketFactory(org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.hc.client5.http.socket.ConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.hc.client5.http.socket.PlainConnectionSocketFactory) BasicLineParser(org.apache.hc.core5.http.message.BasicLineParser) LineParser(org.apache.hc.core5.http.message.LineParser) HttpHost(org.apache.hc.core5.http.HttpHost) DefaultHttpResponseParser(org.apache.hc.core5.http.impl.io.DefaultHttpResponseParser) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) ManagedHttpClientConnectionFactory(org.apache.hc.client5.http.impl.io.ManagedHttpClientConnectionFactory) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) DnsResolver(org.apache.hc.client5.http.DnsResolver) SystemDefaultDnsResolver(org.apache.hc.client5.http.SystemDefaultDnsResolver) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) SocketConfig(org.apache.hc.core5.http.io.SocketConfig) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) BasicLineParser(org.apache.hc.core5.http.message.BasicLineParser) SSLContext(javax.net.ssl.SSLContext) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) CredentialsProvider(org.apache.hc.client5.http.auth.CredentialsProvider) DefaultHttpRequestWriterFactory(org.apache.hc.core5.http.impl.io.DefaultHttpRequestWriterFactory) PoolingHttpClientConnectionManager(org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager) DefaultHttpResponseParserFactory(org.apache.hc.core5.http.impl.io.DefaultHttpResponseParserFactory) ManagedHttpClientConnection(org.apache.hc.client5.http.io.ManagedHttpClientConnection) HttpRoute(org.apache.hc.client5.http.HttpRoute) CookieStore(org.apache.hc.client5.http.cookie.CookieStore) BasicCookieStore(org.apache.hc.client5.http.cookie.BasicCookieStore) BasicCookieStore(org.apache.hc.client5.http.cookie.BasicCookieStore) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) ParseException(org.apache.hc.core5.http.ParseException) InetAddress(java.net.InetAddress) Http1Config(org.apache.hc.core5.http.config.Http1Config) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Aggregations

SocketConfig (org.apache.hc.core5.http.io.SocketConfig)8 HttpServer (org.apache.hc.core5.http.impl.bootstrap.HttpServer)6 IOException (java.io.IOException)4 HttpException (org.apache.hc.core5.http.HttpException)3 HttpHost (org.apache.hc.core5.http.HttpHost)3 SocketTimeoutException (java.net.SocketTimeoutException)2 SSLContext (javax.net.ssl.SSLContext)2 SSLConnectionSocketFactory (org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory)2 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)2 ConnectionClosedException (org.apache.hc.core5.http.ConnectionClosedException)2 ExceptionListener (org.apache.hc.core5.http.ExceptionListener)2 HttpConnection (org.apache.hc.core5.http.HttpConnection)2 ServerBootstrap (org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap)2 InetAddress (java.net.InetAddress)1 URISyntaxException (java.net.URISyntaxException)1 URL (java.net.URL)1 TimeUnit (java.util.concurrent.TimeUnit)1 DnsResolver (org.apache.hc.client5.http.DnsResolver)1 HttpRoute (org.apache.hc.client5.http.HttpRoute)1 SystemDefaultDnsResolver (org.apache.hc.client5.http.SystemDefaultDnsResolver)1