1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.hc.client5.testing.async;
28
29 import static org.hamcrest.MatcherAssert.assertThat;
30
31 import java.util.concurrent.Future;
32 import java.util.concurrent.atomic.AtomicReference;
33
34 import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
35 import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
36 import org.apache.hc.client5.http.config.TlsConfig;
37 import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
38 import org.apache.hc.core5.http.HttpHost;
39 import org.apache.hc.core5.http.HttpVersion;
40 import org.apache.hc.core5.http.ProtocolVersion;
41 import org.apache.hc.core5.http.URIScheme;
42 import org.apache.hc.core5.http.config.Http1Config;
43 import org.apache.hc.core5.http2.HttpVersionPolicy;
44 import org.apache.hc.core5.http2.config.H2Config;
45 import org.apache.hc.core5.testing.nio.H2TestServer;
46 import org.hamcrest.CoreMatchers;
47 import org.junit.jupiter.api.Test;
48
49 public abstract class TestHttpAsyncProtocolPolicy extends AbstractIntegrationTestBase {
50
51 private final HttpVersion version;
52
53 public TestHttpAsyncProtocolPolicy(final URIScheme scheme, final HttpVersion version) {
54 super(scheme);
55 this.version = version;
56 }
57
58 @Test
59 public void testRequestContext() throws Exception {
60 final H2TestServer server;
61 if (version.greaterEquals(HttpVersion.HTTP_2)) {
62 server = startServer(H2Config.DEFAULT, null, null);
63 } else {
64 server = startServer(Http1Config.DEFAULT, null, null);
65 }
66 server.register("/random/*", AsyncRandomHandler::new);
67 final HttpHost target = targetHost();
68
69 final AtomicReference<ProtocolVersion> versionRef = new AtomicReference<>();
70 final CloseableHttpAsyncClient client = startClient(
71 builder -> builder
72 .setDefaultTlsConfig(TlsConfig.custom()
73 .setVersionPolicy(version.greaterEquals(HttpVersion.HTTP_2) ? HttpVersionPolicy.FORCE_HTTP_2 : HttpVersionPolicy.FORCE_HTTP_1)
74 .build()),
75 builder -> builder
76 .addRequestInterceptorFirst((request, entity, context) ->
77 versionRef.set(context.getProtocolVersion())
78 ));
79
80 final Future<SimpleHttpResponse> future = client.execute(
81 SimpleRequestBuilder.get()
82 .setHttpHost(target)
83 .setPath("/random/2048")
84 .build(), null);
85 final SimpleHttpResponse response = future.get();
86 assertThat(response, CoreMatchers.notNullValue());
87 assertThat(response.getCode(), CoreMatchers.equalTo(200));
88 final String body = response.getBodyText();
89 assertThat(body, CoreMatchers.notNullValue());
90 assertThat(body.length(), CoreMatchers.equalTo(2048));
91 assertThat(versionRef.get(), CoreMatchers.equalTo(version));
92 }
93
94 }