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]);
}
}
}
}
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"));
}
}
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());
}
}
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;
}
}
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");
}
Aggregations