简体   繁体   中英

Every second request using Apache HTTPClient fails

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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