Search in sources :

Example 41 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.

the class TestSimpleMessageBuilders method testGetParameters.

@Test
public void testGetParameters() throws Exception {
    final SimpleRequestBuilder builder = SimpleRequestBuilder.get(URI.create("https://host:3456/stuff?p0=p0"));
    builder.addParameter("p1", "v1");
    builder.addParameters(new BasicNameValuePair("p2", "v2"), new BasicNameValuePair("p3", "v3"));
    builder.addParameter(new BasicNameValuePair("p3", "v3.1"));
    Assertions.assertEquals("GET", builder.getMethod());
    Assertions.assertEquals("https", builder.getScheme());
    Assertions.assertEquals(new URIAuthority("host", 3456), builder.getAuthority());
    Assertions.assertEquals("/stuff?p0=p0", builder.getPath());
    assertThat(builder.getParameters(), NameValuePairsMatcher.same(new BasicNameValuePair("p1", "v1"), new BasicNameValuePair("p2", "v2"), new BasicNameValuePair("p3", "v3"), new BasicNameValuePair("p3", "v3.1")));
    final SimpleHttpRequest request = builder.build();
    assertThat(request.getPath(), CoreMatchers.equalTo("/stuff?p0=p0&p1=v1&p2=v2&p3=v3&p3=v3.1"));
    Assertions.assertNull(request.getBody());
}
Also used : URIAuthority(org.apache.hc.core5.net.URIAuthority) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) Test(org.junit.jupiter.api.Test)

Example 42 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.

the class RequestAddCookies method process.

@Override
public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException {
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");
    final String method = request.getMethod();
    if (Method.CONNECT.isSame(method) || Method.TRACE.isSame(method)) {
        return;
    }
    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final String exchangeId = clientContext.getExchangeId();
    // Obtain cookie store
    final CookieStore cookieStore = clientContext.getCookieStore();
    if (cookieStore == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("{} Cookie store not specified in HTTP context", exchangeId);
        }
        return;
    }
    // Obtain the registry of cookie specs
    final Lookup<CookieSpecFactory> registry = clientContext.getCookieSpecRegistry();
    if (registry == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("{} CookieSpec registry not specified in HTTP context", exchangeId);
        }
        return;
    }
    // Obtain the route (required)
    final RouteInfo route = clientContext.getHttpRoute();
    if (route == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("{} Connection route not set in the context", exchangeId);
        }
        return;
    }
    final RequestConfig config = clientContext.getRequestConfig();
    String cookieSpecName = config.getCookieSpec();
    if (cookieSpecName == null) {
        cookieSpecName = StandardCookieSpec.STRICT;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("{} Cookie spec selected: {}", exchangeId, cookieSpecName);
    }
    final URIAuthority authority = request.getAuthority();
    String path = request.getPath();
    if (TextUtils.isEmpty(path)) {
        path = "/";
    }
    String hostName = authority != null ? authority.getHostName() : null;
    if (hostName == null) {
        hostName = route.getTargetHost().getHostName();
    }
    int port = authority != null ? authority.getPort() : -1;
    if (port < 0) {
        port = route.getTargetHost().getPort();
    }
    final CookieOrigin cookieOrigin = new CookieOrigin(hostName, port, path, route.isSecure());
    // Get an instance of the selected cookie policy
    final CookieSpecFactory factory = registry.lookup(cookieSpecName);
    if (factory == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("{} Unsupported cookie spec: {}", exchangeId, cookieSpecName);
        }
        return;
    }
    final CookieSpec cookieSpec = factory.create(clientContext);
    // Get all cookies available in the HTTP state
    final List<Cookie> cookies = cookieStore.getCookies();
    // Find cookies matching the given origin
    final List<Cookie> matchedCookies = new ArrayList<>();
    final Instant now = Instant.now();
    boolean expired = false;
    for (final Cookie cookie : cookies) {
        if (!cookie.isExpired(now)) {
            if (cookieSpec.match(cookie, cookieOrigin)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("{} Cookie {} match {}", exchangeId, cookie, cookieOrigin);
                }
                matchedCookies.add(cookie);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("{} Cookie {} expired", exchangeId, cookie);
            }
            expired = true;
        }
    }
    // exists in the cookie store
    if (expired) {
        cookieStore.clearExpired(now);
    }
    // Generate Cookie request headers
    if (!matchedCookies.isEmpty()) {
        final List<Header> headers = cookieSpec.formatCookies(matchedCookies);
        for (final Header header : headers) {
            request.addHeader(header);
        }
    }
    // Stick the CookieSpec and CookieOrigin instances to the HTTP context
    // so they could be obtained by the response interceptor
    context.setAttribute(HttpClientContext.COOKIE_SPEC, cookieSpec);
    context.setAttribute(HttpClientContext.COOKIE_ORIGIN, cookieOrigin);
}
Also used : Cookie(org.apache.hc.client5.http.cookie.Cookie) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) URIAuthority(org.apache.hc.core5.net.URIAuthority) Instant(java.time.Instant) ArrayList(java.util.ArrayList) CookieStore(org.apache.hc.client5.http.cookie.CookieStore) Header(org.apache.hc.core5.http.Header) CookieSpecFactory(org.apache.hc.client5.http.cookie.CookieSpecFactory) StandardCookieSpec(org.apache.hc.client5.http.cookie.StandardCookieSpec) CookieSpec(org.apache.hc.client5.http.cookie.CookieSpec) CookieOrigin(org.apache.hc.client5.http.cookie.CookieOrigin) RouteInfo(org.apache.hc.client5.http.RouteInfo)

Example 43 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.

the class CachingExec method execute.

@Override
public ClassicHttpResponse execute(final ClassicHttpRequest request, final ExecChain.Scope scope, final ExecChain chain) throws IOException, HttpException {
    Args.notNull(request, "HTTP request");
    Args.notNull(scope, "Scope");
    final HttpRoute route = scope.route;
    final HttpClientContext context = scope.clientContext;
    context.setAttribute(HttpClientContext.HTTP_ROUTE, scope.route);
    context.setAttribute(HttpClientContext.HTTP_REQUEST, request);
    final URIAuthority authority = request.getAuthority();
    final String scheme = request.getScheme();
    final HttpHost target = authority != null ? new HttpHost(scheme, authority) : route.getTargetHost();
    final String via = generateViaHeader(request);
    // default response context
    setResponseStatus(context, CacheResponseStatus.CACHE_MISS);
    if (clientRequestsOurOptions(request)) {
        setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
        return new BasicClassicHttpResponse(HttpStatus.SC_NOT_IMPLEMENTED);
    }
    final SimpleHttpResponse fatalErrorResponse = getFatallyNonCompliantResponse(request, context);
    if (fatalErrorResponse != null) {
        return convert(fatalErrorResponse, scope);
    }
    requestCompliance.makeRequestCompliant(request);
    request.addHeader("Via", via);
    if (!cacheableRequestPolicy.isServableFromCache(request)) {
        LOG.debug("Request is not servable from cache");
        responseCache.flushCacheEntriesInvalidatedByRequest(target, request);
        return callBackend(target, request, scope, chain);
    }
    final HttpCacheEntry entry = responseCache.getCacheEntry(target, request);
    if (entry == null) {
        LOG.debug("Cache miss");
        return handleCacheMiss(target, request, scope, chain);
    } else {
        return handleCacheHit(target, request, scope, chain, entry);
    }
}
Also used : HttpRoute(org.apache.hc.client5.http.HttpRoute) HttpCacheEntry(org.apache.hc.client5.http.cache.HttpCacheEntry) URIAuthority(org.apache.hc.core5.net.URIAuthority) HttpHost(org.apache.hc.core5.http.HttpHost) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse)

Example 44 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.

the class TestClientAuthentication method testAuthenticationCredentialsCachingReauthenticationOnDifferentRealm.

@Test
public void testAuthenticationCredentialsCachingReauthenticationOnDifferentRealm() throws Exception {
    this.server.registerHandler("*", new EchoHandler());
    final HttpHost target = start(new Authenticator() {

        @Override
        public boolean authenticate(final URIAuthority authority, final String requestUri, final String credentials) {
            if (requestUri.equals("/this")) {
                return "test:this".equals(credentials);
            } else if (requestUri.equals("/that")) {
                return "test:that".equals(credentials);
            } else {
                return "test:test".equals(credentials);
            }
        }

        @Override
        public String getRealm(final URIAuthority authority, final String requestUri) {
            if (requestUri.equals("/this")) {
                return "this realm";
            } else if (requestUri.equals("/that")) {
                return "that realm";
            } else {
                return "test realm";
            }
        }
    });
    final DefaultAuthenticationStrategy authStrategy = Mockito.spy(new DefaultAuthenticationStrategy());
    final CredentialsProvider credsProvider = CredentialsProviderBuilder.create().add(new AuthScope(target, "this realm", null), "test", "this".toCharArray()).add(new AuthScope(target, "that realm", null), "test", "that".toCharArray()).build();
    this.clientBuilder.setTargetAuthenticationStrategy(authStrategy);
    this.httpclient = this.clientBuilder.build();
    final HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    final HttpGet httpget1 = new HttpGet("/this");
    this.httpclient.execute(target, httpget1, context, response -> {
        final HttpEntity entity1 = response.getEntity();
        Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
        Assertions.assertNotNull(entity1);
        EntityUtils.consume(entity1);
        return null;
    });
    final HttpGet httpget2 = new HttpGet("/this");
    this.httpclient.execute(target, httpget2, context, response -> {
        final HttpEntity entity2 = response.getEntity();
        Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
        Assertions.assertNotNull(entity2);
        EntityUtils.consume(entity2);
        return null;
    });
    final HttpGet httpget3 = new HttpGet("/that");
    this.httpclient.execute(target, httpget3, context, response -> {
        final HttpEntity entity3 = response.getEntity();
        Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
        Assertions.assertNotNull(entity3);
        EntityUtils.consume(entity3);
        return null;
    });
    Mockito.verify(authStrategy, Mockito.times(2)).select(Mockito.any(), Mockito.any(), Mockito.any());
}
Also used : URIAuthority(org.apache.hc.core5.net.URIAuthority) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpHost(org.apache.hc.core5.http.HttpHost) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) AuthScope(org.apache.hc.client5.http.auth.AuthScope) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) EchoHandler(org.apache.hc.client5.testing.classic.EchoHandler) DefaultAuthenticationStrategy(org.apache.hc.client5.http.impl.DefaultAuthenticationStrategy) CredentialsProvider(org.apache.hc.client5.http.auth.CredentialsProvider) Authenticator(org.apache.hc.client5.testing.auth.Authenticator) BasicTestAuthenticator(org.apache.hc.client5.testing.BasicTestAuthenticator) Test(org.junit.Test)

Example 45 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.

the class AuthenticatingDecorator method handle.

@Override
public void handle(final ClassicHttpRequest request, final ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
    final Header h = request.getFirstHeader(HttpHeaders.AUTHORIZATION);
    final String challengeResponse = h != null ? authTokenExtractor.extract(h.getValue()) : null;
    final URIAuthority authority = request.getAuthority();
    final String requestUri = request.getRequestUri();
    final boolean authenticated = authenticator.authenticate(authority, requestUri, challengeResponse);
    final Header expect = request.getFirstHeader(HttpHeaders.EXPECT);
    final boolean expectContinue = expect != null && "100-continue".equalsIgnoreCase(expect.getValue());
    if (authenticated) {
        if (expectContinue) {
            responseTrigger.sendInformation(new BasicClassicHttpResponse(HttpStatus.SC_CONTINUE));
        }
        requestHandler.handle(request, responseTrigger, context);
    } else {
        final ClassicHttpResponse unauthorized = new BasicClassicHttpResponse(HttpStatus.SC_UNAUTHORIZED);
        final String realm = authenticator.getRealm(authority, requestUri);
        unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, StandardAuthScheme.BASIC + " realm=\"" + realm + "\"");
        customizeUnauthorizedResponse(unauthorized);
        if (unauthorized.getEntity() == null) {
            unauthorized.setEntity(new StringEntity("Unauthorized"));
        }
        if (expectContinue || request.getEntity() == null) {
            // Respond immediately
            responseTrigger.submitResponse(unauthorized);
            // Consume request body later
            EntityUtils.consume(request.getEntity());
        } else {
            // Consume request body first
            EntityUtils.consume(request.getEntity());
            // Respond later
            responseTrigger.submitResponse(unauthorized);
        }
    }
}
Also used : BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) URIAuthority(org.apache.hc.core5.net.URIAuthority) Header(org.apache.hc.core5.http.Header) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse)

Aggregations

URIAuthority (org.apache.hc.core5.net.URIAuthority)63 Test (org.junit.jupiter.api.Test)32 HttpRequest (org.apache.hc.core5.http.HttpRequest)21 HttpHost (org.apache.hc.core5.http.HttpHost)17 Header (org.apache.hc.core5.http.Header)15 URI (java.net.URI)14 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)11 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)10 HttpException (org.apache.hc.core5.http.HttpException)9 IOException (java.io.IOException)8 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)8 ProtocolException (org.apache.hc.core5.http.ProtocolException)8 HttpResponse (org.apache.hc.core5.http.HttpResponse)7 BasicClassicHttpResponse (org.apache.hc.core5.http.message.BasicClassicHttpResponse)7 HttpEntity (org.apache.hc.core5.http.HttpEntity)6 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)6 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)6 HttpRoute (org.apache.hc.client5.http.HttpRoute)5 SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)5 BasicClassicHttpRequest (org.apache.hc.core5.http.message.BasicClassicHttpRequest)5