Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CloseableHttpClient: connection hangs forever

Tags:

httpclient

I have a problem with a connection managed by CloseableHttpClient. A Spring service manages ny connection:

@Service
public class MyService {
...
    private CloseableHttpClient closeableHttpClient;

    public String setPayment() {
...
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader(ACCEPT, APP_JSON);
            httpPost.setHeader(CONTENT_TYPE, APP_JSON);
            StringEntity entity = new StringEntity(request, CHARSET);
            httpPost.setEntity(entity);
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            logger.info("Execution");
        } catch (IOException e) {
            logger.error("Error");
        }
    }
}

My setPayment method is called max 3 times when execution is not successful. Sometimes after the first execution my method hangs with no response. Any suggestion is welcomed.

like image 902
Luca Gavazzeni Avatar asked Feb 14 '18 10:02

Luca Gavazzeni


1 Answers

I suggest you to do the following:

1) set timeout in a constructor:

public MyService() {
        int timeout = 180;      
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(timeout * 1000)
                .setConnectionRequestTimeout(timeout * 1000)
                .setSocketTimeout(timeout * 1000).build();
        closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

2) use try-with-resources to manage CloseableHttpResponse

    public String setPayment() {
    ...

                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader(ACCEPT, APP_JSON);
                httpPost.setHeader(CONTENT_TYPE, APP_JSON);
                StringEntity entity = new StringEntity(request, CHARSET);
                httpPost.setEntity(entity);
try (CloseableHttpResponse response = closeableHttpClient.execute(httpPost)){                
                logger.info("Execution");
            } catch (IOException e) {
                logger.error("Error");
            }
        }
like image 196
Nicola Ben Avatar answered Oct 19 '22 22:10

Nicola Ben