Search in sources :

Example 6 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class ClassicIntegrationTest method testSimpleHttpPostsHTTP10.

/**
 * This test case executes a series of simple HTTP/1.0 POST requests.
 */
@Test
public void testSimpleHttpPostsHTTP10() throws Exception {
    final int reqNo = 20;
    final Random rnd = new Random();
    // Prepare some random data
    final List<byte[]> testData = new ArrayList<>(reqNo);
    for (int i = 0; i < reqNo; i++) {
        final int size = rnd.nextInt(5000);
        final byte[] data = new byte[size];
        rnd.nextBytes(data);
        testData.add(data);
    }
    // Initialize the server-side request handler
    this.server.registerHandler("*", (request, response, context) -> {
        final HttpEntity entity = request.getEntity();
        if (entity != null) {
            final byte[] data = EntityUtils.toByteArray(entity);
            response.setEntity(new ByteArrayEntity(data, null));
        }
        if (HttpVersion.HTTP_1_0.equals(request.getVersion())) {
            response.addHeader("Version", "1.0");
        }
    });
    this.server.start();
    this.client.start();
    final HttpCoreContext context = HttpCoreContext.create();
    final HttpHost host = new HttpHost(scheme.id, "localhost", this.server.getPort());
    for (int r = 0; r < reqNo; r++) {
        // Set protocol level to HTTP/1.0
        final BasicClassicHttpRequest post = new BasicClassicHttpRequest(Method.POST, "/");
        post.setVersion(HttpVersion.HTTP_1_0);
        final byte[] data = testData.get(r);
        post.setEntity(new ByteArrayEntity(data, null));
        try (final ClassicHttpResponse response = this.client.execute(host, post, context)) {
            Assertions.assertEquals(HttpVersion.HTTP_1_1, response.getVersion());
            final Header h1 = response.getFirstHeader("Version");
            Assertions.assertNotNull(h1);
            Assertions.assertEquals("1.0", h1.getValue());
            final byte[] received = EntityUtils.toByteArray(response.getEntity());
            final byte[] expected = testData.get(r);
            Assertions.assertEquals(expected.length, received.length);
            for (int i = 0; i < expected.length; i++) {
                Assertions.assertEquals(expected[i], received[i]);
            }
        }
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) Random(java.util.Random) HttpEntity(org.apache.hc.core5.http.HttpEntity) AbstractHttpEntity(org.apache.hc.core5.http.io.entity.AbstractHttpEntity) ByteArrayEntity(org.apache.hc.core5.http.io.entity.ByteArrayEntity) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) Header(org.apache.hc.core5.http.Header) HttpHost(org.apache.hc.core5.http.HttpHost) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 7 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class ClassicServerAndRequesterTest method testSequentialRequests.

@Test
public void testSequentialRequests() throws Exception {
    server.start();
    final HttpHost target = new HttpHost(scheme.id, "localhost", server.getLocalPort());
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request1 = new BasicClassicHttpRequest(Method.POST, "/stuff");
    request1.setEntity(new StringEntity("some stuff", ContentType.TEXT_PLAIN));
    try (final ClassicHttpResponse response1 = requester.execute(target, request1, TIMEOUT, context)) {
        assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
        final String body1 = EntityUtils.toString(response1.getEntity());
        assertThat(body1, CoreMatchers.equalTo("some stuff"));
    }
    final ClassicHttpRequest request2 = new BasicClassicHttpRequest(Method.POST, "/other-stuff");
    request2.setEntity(new StringEntity("some other stuff", ContentType.TEXT_PLAIN));
    try (final ClassicHttpResponse response2 = requester.execute(target, request2, TIMEOUT, context)) {
        assertThat(response2.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
        final String body2 = EntityUtils.toString(response2.getEntity());
        assertThat(body2, CoreMatchers.equalTo("some other stuff"));
    }
    final ClassicHttpRequest request3 = new BasicClassicHttpRequest(Method.POST, "/more-stuff");
    request3.setEntity(new StringEntity("some more stuff", ContentType.TEXT_PLAIN));
    try (final ClassicHttpResponse response3 = requester.execute(target, request3, TIMEOUT, context)) {
        assertThat(response3.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
        final String body3 = EntityUtils.toString(response3.getEntity());
        assertThat(body3, CoreMatchers.equalTo("some more stuff"));
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) HttpHost(org.apache.hc.core5.http.HttpHost) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) Test(org.junit.Test)

Example 8 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class ClassicServerBootstrapFilterTest method testFilters.

@Test
public void testFilters() throws Exception {
    server.start();
    final HttpHost target = new HttpHost("http", "localhost", server.getLocalPort());
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, "/filters");
    request.setEntity(new StringEntity("some stuff", ContentType.TEXT_PLAIN));
    try (final ClassicHttpResponse response = requester.execute(target, request, TIMEOUT, context)) {
        assertThat(response.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
        final Header testFilterHeader = response.getHeader("X-Test-Filter");
        assertThat(testFilterHeader, CoreMatchers.notNullValue());
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) Header(org.apache.hc.core5.http.Header) HttpHost(org.apache.hc.core5.http.HttpHost) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) Test(org.junit.jupiter.api.Test)

Example 9 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class ClassicTestClientAdapter method execute.

/**
 * {@inheritDoc}
 */
@Override
public Map<String, Object> execute(final String defaultURI, final Map<String, Object> request) throws Exception {
    // check the request for missing items.
    if (defaultURI == null) {
        throw new HttpException("defaultURL cannot be null");
    }
    if (request == null) {
        throw new HttpException("request cannot be null");
    }
    if (!request.containsKey(PATH)) {
        throw new HttpException("Request path should be set.");
    }
    if (!request.containsKey(METHOD)) {
        throw new HttpException("Request method should be set.");
    }
    final Timeout timeout;
    if (request.containsKey(TIMEOUT)) {
        timeout = Timeout.ofMilliseconds((long) request.get(TIMEOUT));
    } else {
        timeout = null;
    }
    final ClassicTestClient client = new ClassicTestClient(SocketConfig.custom().setSoTimeout(timeout).build());
    // Append the path to the defaultURI.
    String tempDefaultURI = defaultURI;
    if (!defaultURI.endsWith("/")) {
        tempDefaultURI += "/";
    }
    final URI startingURI = new URI(tempDefaultURI + request.get(PATH));
    final URI uri;
    // append each parameter in the query to the uri.
    @SuppressWarnings("unchecked") final Map<String, String> queryMap = (Map<String, String>) request.get(QUERY);
    if (queryMap != null) {
        final String existingQuery = startingURI.getRawQuery();
        final StringBuilder newQuery = new StringBuilder(existingQuery == null ? "" : existingQuery);
        // append each parm to the query
        for (final Entry<String, String> parm : queryMap.entrySet()) {
            newQuery.append("&").append(parm.getKey()).append("=").append(parm.getValue());
        }
        // create a uri with the new query.
        uri = new URI(startingURI.getRawSchemeSpecificPart(), startingURI.getRawUserInfo(), startingURI.getHost(), startingURI.getPort(), startingURI.getRawPath(), newQuery.toString(), startingURI.getRawFragment());
    } else {
        uri = startingURI;
    }
    final BasicClassicHttpRequest httpRequest = new BasicClassicHttpRequest(request.get(METHOD).toString(), uri);
    if (request.containsKey(PROTOCOL_VERSION)) {
        httpRequest.setVersion((ProtocolVersion) request.get(PROTOCOL_VERSION));
    }
    // call addHeader for each header in headers.
    @SuppressWarnings("unchecked") final Map<String, String> headersMap = (Map<String, String>) request.get(HEADERS);
    if (headersMap != null) {
        for (final Entry<String, String> header : headersMap.entrySet()) {
            httpRequest.addHeader(header.getKey(), header.getValue());
        }
    }
    // call setEntity if a body is specified.
    final String requestBody = (String) request.get(BODY);
    if (requestBody != null) {
        final String requestContentType = (String) request.get(CONTENT_TYPE);
        final StringEntity entity = requestContentType != null ? new StringEntity(requestBody, ContentType.parse(requestContentType)) : new StringEntity(requestBody);
        httpRequest.setEntity(entity);
    }
    client.start(null);
    // Now start the request.
    final HttpHost host = new HttpHost(uri.getHost(), uri.getPort());
    final HttpCoreContext context = HttpCoreContext.create();
    try (final ClassicHttpResponse response = client.execute(host, httpRequest, context)) {
        // Prepare the response.  It will contain status, body, headers, and contentType.
        final HttpEntity entity = response.getEntity();
        final String body = entity == null ? null : EntityUtils.toString(entity);
        final String contentType = entity == null ? null : entity.getContentType();
        // prepare the returned information
        final Map<String, Object> ret = new HashMap<>();
        ret.put(STATUS, response.getCode());
        // convert the headers to a Map
        final Map<String, Object> headerMap = new HashMap<>();
        for (final Header header : response.getHeaders()) {
            headerMap.put(header.getName(), header.getValue());
        }
        ret.put(HEADERS, headerMap);
        ret.put(BODY, body);
        ret.put(CONTENT_TYPE, contentType);
        return ret;
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpEntity(org.apache.hc.core5.http.HttpEntity) HashMap(java.util.HashMap) Timeout(org.apache.hc.core5.util.Timeout) URI(java.net.URI) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) Header(org.apache.hc.core5.http.Header) HttpHost(org.apache.hc.core5.http.HttpHost) ClassicTestClient(org.apache.hc.core5.testing.classic.ClassicTestClient) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) HttpException(org.apache.hc.core5.http.HttpException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class ClientH2StreamMultiplexer method createLocallyInitiatedStream.

@Override
H2StreamHandler createLocallyInitiatedStream(final ExecutableCommand command, final H2StreamChannel channel, final HttpProcessor httpProcessor, final BasicHttpConnectionMetrics connMetrics) throws IOException {
    if (command instanceof RequestExecutionCommand) {
        final RequestExecutionCommand executionCommand = (RequestExecutionCommand) command;
        final AsyncClientExchangeHandler exchangeHandler = executionCommand.getExchangeHandler();
        final HandlerFactory<AsyncPushConsumer> pushHandlerFactory = executionCommand.getPushHandlerFactory();
        final HttpCoreContext context = HttpCoreContext.adapt(executionCommand.getContext());
        context.setAttribute(HttpCoreContext.SSL_SESSION, getSSLSession());
        context.setAttribute(HttpCoreContext.CONNECTION_ENDPOINT, getEndpointDetails());
        return new ClientH2StreamHandler(channel, httpProcessor, connMetrics, exchangeHandler, pushHandlerFactory != null ? pushHandlerFactory : this.pushHandlerFactory, context);
    }
    throw new H2ConnectionException(H2Error.INTERNAL_ERROR, "Unexpected executable command");
}
Also used : AsyncPushConsumer(org.apache.hc.core5.http.nio.AsyncPushConsumer) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) H2ConnectionException(org.apache.hc.core5.http2.H2ConnectionException) RequestExecutionCommand(org.apache.hc.core5.http.nio.command.RequestExecutionCommand)

Aggregations

HttpCoreContext (org.apache.hc.core5.http.protocol.HttpCoreContext)56 BasicClassicHttpRequest (org.apache.hc.core5.http.message.BasicClassicHttpRequest)46 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)39 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)33 BasicClassicHttpResponse (org.apache.hc.core5.http.message.BasicClassicHttpResponse)29 HttpHost (org.apache.hc.core5.http.HttpHost)26 Test (org.junit.jupiter.api.Test)25 Test (org.junit.Test)21 HttpEntity (org.apache.hc.core5.http.HttpEntity)16 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)13 HttpClientConnection (org.apache.hc.core5.http.io.HttpClientConnection)12 ByteArrayEntity (org.apache.hc.core5.http.io.entity.ByteArrayEntity)12 HttpProcessor (org.apache.hc.core5.http.protocol.HttpProcessor)12 AbstractHttpEntity (org.apache.hc.core5.http.io.entity.AbstractHttpEntity)9 Random (java.util.Random)8 Header (org.apache.hc.core5.http.Header)8 ArrayList (java.util.ArrayList)6 HttpRequest (org.apache.hc.core5.http.HttpRequest)6 ProtocolException (org.apache.hc.core5.http.ProtocolException)6 ContentType (org.apache.hc.core5.http.ContentType)5