Using Apache HttpClient how to set the TIMEOUT on a request and response

后端 未结 2 1646
抹茶落季
抹茶落季 2020-12-13 09:27

I need to set time out for the Http Request we make to a service (not a web service). We are using Apache HTTP Client. I have added these 2 lines of code to set the time ou

2条回答
  •  遥遥无期
    2020-12-13 09:45

    I am guessing many people come here because of the title and because the HttpConnectionParams API is deprecated.

    Using a recent version of Apache HTTP Client, you can set these timeouts using the request params:

    HttpPost request = new HttpPost(url);
    
    RequestConfig requestConfig = RequestConfig.custom()
      .setSocketTimeout(TIMEOUT_MILLIS)
      .setConnectTimeout(TIMEOUT_MILLIS)
      .setConnectionRequestTimeout(TIMEOUT_MILLIS)
      .build();
    
    request.setConfig(requestConfig);
    

    Alternatively, you can also set this when you create your HTTP Client, using the builder API for the HTTP client, but you'll also need to build a custom connection manager with a custom socket config.

    The configuration example file is an excellent resource to find out about how to configure Apache HTTP Client.

提交回复
热议问题