Every second request using Apache HTTPClient fails

隐身守侯 提交于 2019-12-11 03:35:15

问题


I am trying to use Apache HTTPClient 4.5.1 to do some rest requests. Unfortunately every second request ends up in "java.net.SocketTimeoutException: Read timed out" (or hangs forever if the socket timeout is not set).

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):

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. On the server side I have a wildfly 8 (and also 9) running. 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?


回答1:


Thanks to the hint from hotzst to enable logging, I figured it out:

The server was returing a HTTP status 204 (No content), but sent some response data anyway. HttpClient got those response data as "Garbage in response" for the NEXT request, which broke it by screwing up the response headers. Changing the reservers response code to 404 fixes the problem for me.



来源:https://stackoverflow.com/questions/32883783/every-second-request-using-apache-httpclient-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!