Search in sources :

Example 1 with HttpRoutePlanner

use of org.apache.http.conn.routing.HttpRoutePlanner in project connect-sdk-java by Ingenico-ePayments.

the class DefaultConnection method createHttpClient.

private CloseableHttpClient createHttpClient(ProxyConfiguration proxyConfiguration) {
    HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager);
    HttpRoutePlanner routePlanner;
    CredentialsProvider credentialsProvider;
    if (proxyConfiguration != null) {
        HttpHost proxy = new HttpHost(proxyConfiguration.getHost(), proxyConfiguration.getPort(), proxyConfiguration.getScheme());
        routePlanner = new DefaultProxyRoutePlanner(proxy, DefaultSchemePortResolver.INSTANCE);
        credentialsProvider = new BasicCredentialsProvider();
        if (proxyConfiguration.getUsername() != null) {
            AuthScope authscope = new AuthScope(proxyConfiguration.getHost(), proxyConfiguration.getPort());
            final Credentials credentials = new UsernamePasswordCredentials(proxyConfiguration.getUsername(), proxyConfiguration.getPassword());
            credentialsProvider.setCredentials(authscope, credentials);
            // enable preemptive authentication
            HttpRequestInterceptor proxyAuthenticationInterceptor = new HttpRequestInterceptor() {

                @Override
                public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                    Header header = request.getFirstHeader(AUTH.PROXY_AUTH_RESP);
                    if (header == null) {
                        header = new BasicScheme((Charset) null).authenticate(credentials, request, context);
                        if (!AUTH.PROXY_AUTH_RESP.equals(header.getName())) {
                            header = new BasicHeader(AUTH.PROXY_AUTH_RESP, header.getValue());
                        }
                        request.setHeader(header);
                    }
                }
            };
            builder = builder.addInterceptorLast(proxyAuthenticationInterceptor);
        }
    } else {
        // add support for system properties
        routePlanner = new SystemDefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault());
        credentialsProvider = new SystemDefaultCredentialsProvider();
    }
    // add logging - last for requests, first for responses
    LoggingInterceptor loggingInterceptor = new LoggingInterceptor();
    builder = builder.addInterceptorLast((HttpRequestInterceptor) loggingInterceptor);
    builder = builder.addInterceptorFirst((HttpResponseInterceptor) loggingInterceptor);
    return builder.setRoutePlanner(routePlanner).setDefaultCredentialsProvider(credentialsProvider).build();
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) DefaultProxyRoutePlanner(org.apache.http.impl.conn.DefaultProxyRoutePlanner) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) SystemDefaultCredentialsProvider(org.apache.http.impl.client.SystemDefaultCredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Header(org.apache.http.Header) ResponseHeader(com.ingenico.connect.gateway.sdk.java.ResponseHeader) RequestHeader(com.ingenico.connect.gateway.sdk.java.RequestHeader) BasicHeader(org.apache.http.message.BasicHeader) HttpRoutePlanner(org.apache.http.conn.routing.HttpRoutePlanner) HttpHost(org.apache.http.HttpHost) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) AuthScope(org.apache.http.auth.AuthScope) HttpResponseInterceptor(org.apache.http.HttpResponseInterceptor) SystemDefaultCredentialsProvider(org.apache.http.impl.client.SystemDefaultCredentialsProvider) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) BasicHeader(org.apache.http.message.BasicHeader) SystemDefaultRoutePlanner(org.apache.http.impl.conn.SystemDefaultRoutePlanner)

Example 2 with HttpRoutePlanner

use of org.apache.http.conn.routing.HttpRoutePlanner in project dropwizard by dropwizard.

the class HttpClientBuilderTest method checkProxy.

private CloseableHttpClient checkProxy(HttpClientConfiguration config, HttpHost target, @Nullable HttpHost expectedProxy) throws Exception {
    CloseableHttpClient httpClient = builder.using(config).build("test");
    HttpRoutePlanner routePlanner = (HttpRoutePlanner) getInaccessibleField(httpClient.getClass(), "routePlanner").get(httpClient);
    HttpRoute route = routePlanner.determineRoute(target, new HttpGet(target.toURI()), new BasicHttpContext());
    assertThat(route.getProxyHost()).isEqualTo(expectedProxy);
    assertThat(route.getTargetHost()).isEqualTo(target);
    assertThat(route.getHopCount()).isEqualTo(expectedProxy != null ? 2 : 1);
    return httpClient;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpRoute(org.apache.http.conn.routing.HttpRoute) HttpRoutePlanner(org.apache.http.conn.routing.HttpRoutePlanner) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpGet(org.apache.http.client.methods.HttpGet)

Example 3 with HttpRoutePlanner

use of org.apache.http.conn.routing.HttpRoutePlanner in project dropwizard by dropwizard.

the class JerseyClientBuilderTest method usesACustomHttpRoutePlanner.

@Test
void usesACustomHttpRoutePlanner() {
    final HttpRoutePlanner customHttpRoutePlanner = new SystemDefaultRoutePlanner(new ProxySelector() {

        @Override
        public List<Proxy> select(URI uri) {
            return Collections.singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.53.12", 8080)));
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        }
    });
    builder.using(customHttpRoutePlanner);
    verify(apacheHttpClientBuilder).using(customHttpRoutePlanner);
}
Also used : ProxySelector(java.net.ProxySelector) Proxy(java.net.Proxy) HttpRoutePlanner(org.apache.http.conn.routing.HttpRoutePlanner) InetSocketAddress(java.net.InetSocketAddress) List(java.util.List) IOException(java.io.IOException) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) URI(java.net.URI) SystemDefaultRoutePlanner(org.apache.http.impl.conn.SystemDefaultRoutePlanner) Test(org.junit.jupiter.api.Test)

Example 4 with HttpRoutePlanner

use of org.apache.http.conn.routing.HttpRoutePlanner in project vscrawler by virjar.

the class CrawlerSession method decorateRoutePlanner.

private void decorateRoutePlanner(CrawlerHttpClient crawlerHttpClient) {
    HttpRoutePlanner routePlanner = crawlerHttpClient.getRoutePlanner();
    if (!(routePlanner instanceof ProxyBindRoutPlanner)) {
        log.warn("自定义了代理发生器,vscrawler的代理功能将不会生效");
        return;
    }
    VSCrawlerRoutePlanner vsCrawlerRoutePlanner = new VSCrawlerRoutePlanner((ProxyBindRoutPlanner) routePlanner, ipPool, proxyPlanner, this);
    crawlerHttpClient.setRoutePlanner(vsCrawlerRoutePlanner);
}
Also used : VSCrawlerRoutePlanner(com.virjar.vscrawler.core.net.proxy.VSCrawlerRoutePlanner) HttpRoutePlanner(org.apache.http.conn.routing.HttpRoutePlanner) ProxyBindRoutPlanner(com.virjar.dungproxy.client.httpclient.conn.ProxyBindRoutPlanner)

Example 5 with HttpRoutePlanner

use of org.apache.http.conn.routing.HttpRoutePlanner in project fess-crawler by codelibs.

the class HcHttpClient method init.

@Override
public synchronized void init() {
    if (httpClient != null) {
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Initializing " + HcHttpClient.class.getName());
    }
    super.init();
    // robots.txt parser
    final Boolean robotsTxtEnabled = getInitParameter(ROBOTS_TXT_ENABLED_PROPERTY, Boolean.TRUE, Boolean.class);
    if (robotsTxtHelper != null) {
        robotsTxtHelper.setEnabled(robotsTxtEnabled.booleanValue());
    }
    // httpclient
    final org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    final Integer connectionTimeoutParam = getInitParameter(CONNECTION_TIMEOUT_PROPERTY, connectionTimeout, Integer.class);
    if (connectionTimeoutParam != null) {
        requestConfigBuilder.setConnectTimeout(connectionTimeoutParam);
    }
    final Integer soTimeoutParam = getInitParameter(SO_TIMEOUT_PROPERTY, soTimeout, Integer.class);
    if (soTimeoutParam != null) {
        requestConfigBuilder.setSocketTimeout(soTimeoutParam);
    }
    // AuthSchemeFactory
    final RegistryBuilder<AuthSchemeProvider> authSchemeProviderBuilder = RegistryBuilder.create();
    @SuppressWarnings("unchecked") final Map<String, AuthSchemeProvider> factoryMap = getInitParameter(AUTH_SCHEME_PROVIDERS_PROPERTY, authSchemeProviderMap, Map.class);
    if (factoryMap != null) {
        for (final Map.Entry<String, AuthSchemeProvider> entry : factoryMap.entrySet()) {
            authSchemeProviderBuilder.register(entry.getKey(), entry.getValue());
        }
    }
    // user agent
    userAgent = getInitParameter(USER_AGENT_PROPERTY, userAgent, String.class);
    if (StringUtil.isNotBlank(userAgent)) {
        httpClientBuilder.setUserAgent(userAgent);
    }
    final HttpRoutePlanner planner = buildRoutePlanner();
    if (planner != null) {
        httpClientBuilder.setRoutePlanner(planner);
    }
    // Authentication
    final Authentication[] siteCredentialList = getInitParameter(BASIC_AUTHENTICATIONS_PROPERTY, new Authentication[0], Authentication[].class);
    final List<Pair<FormScheme, Credentials>> formSchemeList = new ArrayList<>();
    for (final Authentication authentication : siteCredentialList) {
        final AuthScheme authScheme = authentication.getAuthScheme();
        if (authScheme instanceof FormScheme) {
            formSchemeList.add(new Pair<>((FormScheme) authScheme, authentication.getCredentials()));
        } else {
            final AuthScope authScope = authentication.getAuthScope();
            credentialsProvider.setCredentials(authScope, authentication.getCredentials());
            if (authScope.getHost() != null && authScheme != null) {
                final HttpHost targetHost = new HttpHost(authScope.getHost(), authScope.getPort());
                authCache.put(targetHost, authScheme);
            }
        }
    }
    httpClientContext.setAuthCache(authCache);
    httpClientContext.setCredentialsProvider(credentialsProvider);
    // Request Header
    final RequestHeader[] requestHeaders = getInitParameter(REQUERT_HEADERS_PROPERTY, new RequestHeader[0], RequestHeader[].class);
    for (final RequestHeader requestHeader : requestHeaders) {
        if (requestHeader.isValid()) {
            requestHeaderList.add(new BasicHeader(requestHeader.getName(), requestHeader.getValue()));
        }
    }
    // do not redirect
    requestConfigBuilder.setRedirectsEnabled(getInitParameter(REDIRECTS_ENABLED, redirectsEnabled, Boolean.class));
    // cookie
    if (cookieSpec != null) {
        requestConfigBuilder.setCookieSpec(cookieSpec);
    }
    // cookie store
    httpClientBuilder.setDefaultCookieStore(cookieStore);
    if (cookieStore != null) {
        final Cookie[] cookies = getInitParameter(COOKIES_PROPERTY, new Cookie[0], Cookie[].class);
        for (final Cookie cookie : cookies) {
            cookieStore.addCookie(cookie);
        }
    }
    // cookie registry
    final Lookup<CookieSpecProvider> cookieSpecRegistry = buildCookieSpecRegistry();
    if (cookieSpecRegistry != null) {
        httpClientBuilder.setDefaultCookieSpecRegistry(cookieSpecRegistry);
    }
    // SSL
    final LayeredConnectionSocketFactory sslSocketFactory = buildSSLSocketFactory();
    if (sslSocketFactory != null) {
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
    }
    connectionMonitorTask = TimeoutManager.getInstance().addTimeoutTarget(new HcConnectionMonitorTarget(clientConnectionManager, idleConnectionTimeout), connectionCheckInterval, true);
    final CloseableHttpClient closeableHttpClient = httpClientBuilder.setDnsResolver(dnsResolver).setConnectionManager(clientConnectionManager).setDefaultRequestConfig(requestConfigBuilder.build()).build();
    if (!httpClientPropertyMap.isEmpty()) {
        final BeanDesc beanDesc = BeanDescFactory.getBeanDesc(closeableHttpClient.getClass());
        for (final Map.Entry<String, Object> entry : httpClientPropertyMap.entrySet()) {
            final String propertyName = entry.getKey();
            if (beanDesc.hasPropertyDesc(propertyName)) {
                final PropertyDesc propertyDesc = beanDesc.getPropertyDesc(propertyName);
                propertyDesc.setValue(closeableHttpClient, entry.getValue());
            } else {
                logger.warn("DefaultHttpClient does not have " + propertyName + ".");
            }
        }
    }
    formSchemeList.forEach(p -> {
        final FormScheme scheme = p.getFirst();
        final Credentials credentials = p.getSecond();
        scheme.authenticate(credentials, (request, consumer) -> {
            // request header
            for (final Header header : requestHeaderList) {
                request.addHeader(header);
            }
            HttpEntity httpEntity = null;
            try {
                final HttpResponse response = closeableHttpClient.execute(request, new BasicHttpContext(httpClientContext));
                httpEntity = response.getEntity();
                consumer.accept(response, httpEntity);
            } catch (final Exception e) {
                request.abort();
                logger.warn("Failed to authenticate on " + scheme, e);
            } finally {
                EntityUtils.consumeQuietly(httpEntity);
            }
        });
    });
    httpClient = closeableHttpClient;
}
Also used : HttpEntity(org.apache.http.HttpEntity) LayeredConnectionSocketFactory(org.apache.http.conn.socket.LayeredConnectionSocketFactory) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) ArrayList(java.util.ArrayList) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) AuthScheme(org.apache.http.auth.AuthScheme) HttpRoutePlanner(org.apache.http.conn.routing.HttpRoutePlanner) HttpHost(org.apache.http.HttpHost) BeanDesc(org.codelibs.core.beans.BeanDesc) PropertyDesc(org.codelibs.core.beans.PropertyDesc) Pair(org.codelibs.core.misc.Pair) Cookie(org.apache.http.cookie.Cookie) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpResponse(org.apache.http.HttpResponse) CrawlingAccessException(org.codelibs.fess.crawler.exception.CrawlingAccessException) MaxLengthExceededException(org.codelibs.fess.crawler.exception.MaxLengthExceededException) CrawlerSystemException(org.codelibs.fess.crawler.exception.CrawlerSystemException) ParseException(java.text.ParseException) NoRouteToHostException(java.net.NoRouteToHostException) SocketException(java.net.SocketException) ConnectException(java.net.ConnectException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) AuthScope(org.apache.http.auth.AuthScope) CookieSpecProvider(org.apache.http.cookie.CookieSpecProvider) DefaultCookieSpecProvider(org.apache.http.impl.cookie.DefaultCookieSpecProvider) RFC6265CookieSpecProvider(org.apache.http.impl.cookie.RFC6265CookieSpecProvider) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) Map(java.util.Map) HashMap(java.util.HashMap) FormScheme(org.codelibs.fess.crawler.client.http.form.FormScheme) BasicHeader(org.apache.http.message.BasicHeader) Credentials(org.apache.http.auth.Credentials)

Aggregations

HttpRoutePlanner (org.apache.http.conn.routing.HttpRoutePlanner)8 HttpHost (org.apache.http.HttpHost)4 IOException (java.io.IOException)3 AuthScope (org.apache.http.auth.AuthScope)3 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)3 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)3 SystemDefaultRoutePlanner (org.apache.http.impl.conn.SystemDefaultRoutePlanner)3 InetSocketAddress (java.net.InetSocketAddress)2 Proxy (java.net.Proxy)2 ProxySelector (java.net.ProxySelector)2 SocketAddress (java.net.SocketAddress)2 URI (java.net.URI)2 List (java.util.List)2 Header (org.apache.http.Header)2 Credentials (org.apache.http.auth.Credentials)2 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)2 CredentialsProvider (org.apache.http.client.CredentialsProvider)2 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)2 DefaultProxyRoutePlanner (org.apache.http.impl.conn.DefaultProxyRoutePlanner)2 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)2