问题
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