DefaultHttpClient keep alive connection on multiple requests

末鹿安然 提交于 2019-12-21 06:18:27

问题


I'm using the DefaultHttpClient to make numerous requests to the same URL with basic authentication.

Something like this:

for (String json: listOfItems)
{
    DefaultHttpClient client = new DefaultHttpClient();

    try
    {       
       client.getCredentialsProvider().setCredentials(
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "basic"),
                    new UsernamePasswordCredentials(user, pass));

       HttpPost request = new HttpPost(path);
       setHeaders(request);

       StringEntity se = new StringEntity(json, HTTP.UTF_8);
       se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
       request.setEntity(se);

       client.execute(request);    
    }       
    finally
    {
       // close/release connection
       client.getConnectionManager().shutdown();            
    }
}

My question is what is the best way to keep alive the connection while doing this. So I don't need to close the connection on each post request.


回答1:


You might need to add the Socket_Timeout parameter and implement a KeepAlive strategy, which are detailed over here -

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e652



来源:https://stackoverflow.com/questions/9904040/defaulthttpclient-keep-alive-connection-on-multiple-requests

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