简体   繁体   English

每隔一个使用 Apache HTTPClient 的请求就会失败

[英]Every second request using Apache HTTPClient fails

I am trying to use Apache HTTPClient 4.5.1 to do some rest requests.我正在尝试使用 Apache HTTPClient 4.5.1 来做一些休息请求。 Unfortunately every second request ends up in "java.net.SocketTimeoutException: Read timed out" (or hangs forever if the socket timeout is not set).不幸的是,每第二个请求都以“java.net.SocketTimeoutException: Read timed out”结束(如果未设置套接字超时,则永远挂起)。

I am building my client like this:我正在像这样构建我的客户端:

ConnectionSocketFactory sf = new PlainConnectionSocketFactory();

Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory> create()
    .register("http", sf)
    .build();

Lookup<AuthSchemeProvider> authProviders = RegistryBuilder.<AuthSchemeProvider> create()
    .register(AuthSchemes.BASIC, (AuthSchemeProvider) new BasicSchemeFactory())
    .build();

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);

CredentialsProvider cp = new BasicCredentialsProvider();
cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "pass"));

RequestConfig requestConfig = RequestConfig.custom()
    .setConnectTimeout(15000)
    .setConnectionRequestTimeout(15000)
    .setSocketTimeout(15000)
    .build();

this.client = HttpClients.custom()
    .setConnectionManager(cm)
    .setDefaultCredentialsProvider(cp)
    .setDefaultAuthSchemeRegistry(authProviders)
    .setDefaultRequestConfig(requestConfig)
    .build();

Afterwards I do my requests like this (on the same HttpClient instance):之后我做我这样的请求(在同一个 HttpClient 实例上):

HttpDelete delete = new HttpDelete(uri);

HttpClientContext context = HttpClientContext.create();
CloseableHttpResponse response = this.client.execute(request, context);
try {
    int statusCode = response.getStatusLine().getStatusCode();
    return statusCode;
}
finally {
    response.close();
}

Everything works fine if I start using a new HttpClient instance for every request.如果我开始为每个请求使用一个新的 HttpClient 实例,一切正常。 On the server side I have a wildfly 8 (and also 9) running.在服务器端,我有一个 wildfly 8(还有 9)在运行。 For the second request I cannot even see a request incoming, so to me it looks like the client is not even trying.对于第二个请求,我什至看不到请求传入,因此在我看来,客户端甚至没有尝试。

Any ideas on what I am missing/doing wrong?关于我遗漏/做错了什么的任何想法?

Thanks to the hint from hotzst to enable logging, I figured it out:感谢hotzst提示启用日志记录,我想通了:

The server was returing a HTTP status 204 (No content), but sent some response data anyway.服务器正在返回 HTTP 状态 204(无内容),但还是发送了一些响应数据。 HttpClient got those response data as "Garbage in response" for the NEXT request, which broke it by screwing up the response headers. HttpClient 将这些响应数据作为 NEXT 请求的“响应中的垃圾”获取,这通过弄乱响应标头来破坏它。 Changing the reservers response code to 404 fixes the problem for me.将储备者响应代码更改为 404 可以解决我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM