【发布时间】:2021-06-01 00:40:41
【问题描述】:
我有一个小样本 servlet 部署到 Tomcat,它将回显任何接收到的参数。 Tomcat 配置为支持 HTTP/1.1 和 HTTP/2。我可以使用curl 向 servlet 发出 GET 请求,证明它可以在 HTTP/1.1 和 HTTP/2 上工作。
使用 Apache HTTP 5.0 客户端我有一个单元测试来命中 servlet 和 POST 一个带有一些参数(请求内容)的请求,它工作正常 - 服务器接收参数并将它们返回给我可以的客户端阅读它们。在此测试中,我使用CloseableHttpAsyncClient.setVersionPolicy() 调用调用客户端以使用HTTP/1.1 或HTTP/2。但是,如果我更改为使用 HTTP/2,则客户端不会将请求内容发送到服务器。
下面是成功调用 HTTP/1.1 的示例代码 - 你可以看到我有 setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_1)。如果我将其更改为 FORCE_HTTP_2,则通过 HTTP/2.0 进行调用,但不会发送请求内容。
谁能建议我做错了什么或我需要做些什么额外的事情?我没有找到很多关于使用新的 Apache 5.0 客户端库的文档,而且这些示例没有显示发送和 POST 内容(或者至少是我能找到的那些)。
public void testWithHTTP1() throws Exception {
final String content = "Code=99&Message=Hello";
final String contentType = "application/text";
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_1)
.build();
client.start();
final HttpHost target = new HttpHost("http","localhost",8002);
final String requestUri = "/VSFTestMT_Test/Test/Test_EchoHttpGet";
final HttpClientContext clientContext = HttpClientContext.create();
final SimpleHttpRequest httppost = SimpleHttpRequests.post(target, requestUri);
httppost.setBody(content, ContentType.create("application.x_www_form_urlencoded"));
final Future<SimpleHttpResponse> future = client.execute(
httppost,
clientContext,
new FutureCallback<SimpleHttpResponse>() {
@Override
public void completed(final SimpleHttpResponse response) {
System.out.println(requestUri + "->" + response.getCode());
System.out.println(response.getBody());
}
@Override
public void failed(final Exception ex) {
System.out.println(requestUri + "->" + ex);
}
@Override
public void cancelled() {
System.out.println(requestUri + " cancelled");
}
});
System.out.println("Shutting down");
client.close(CloseMode.GRACEFUL);
}
【问题讨论】:
-
在此处或将会话的线路日志发布到 httpclient-users@hc.apache.org
标签: java http2 apache-httpcomponents apache-httpasyncclient apache-httpclient-5.x