On Sun, 2015-02-15 at 11:55 +0800, [email protected] wrote: > Can someone take a look at my question, thanks. > >
HC 3.1 is at the end of life and is no longer supported. Oleg > > > > From: [email protected] > Date: 2015-02-09 17:10 > To: httpclient-users > Subject: The two ways to use HttpClient > Hi experts, > > I am now using httpclient to send http request, approximately 1000 requests > per seconds. I am using 3.1, and come up with following two ways, I would ask > which one will gain better performance, perhaps both have its problems(You > know, connections is closed or released or someting else) I am glad if you > point it to me, thanks. > > 1. Create a new HttpClient each time before sending request,as: > private HttpClient newHttpClient() { > HttpClient client = new HttpClient(); > > client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT); > client.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT); > return client; > } > public String post(String url, String postData, String contentType) throws > IOException { > String encoding = HTTP.UTF_8; > StringRequestEntity entity = new StringRequestEntity(postData, > contentType, encoding); > PostMethod pm = new PostMethod(url); > pm.setRequestHeader("Connection", "close"); //Make sure the > connection is closed when releaseConnection is called. > pm.setRequestEntity(entity); > try { > HttpClient client = newHttpClient(); //Create a new HttpClient > client.executeMethod(pm); > String response = responseBodyAsString(pm); //consume the response > return response; > } finally { > pm.releaseConnection(); //release the connection > } > } > > 2. use MultiThreadedHttpConnectionManager, as following(The HttpClient is a > static instance that will be reused by many threads) > > private HttpClientUtilV2() { > MultiThreadedHttpConnectionManager connectionManager = new > MultiThreadedHttpConnectionManager(); > HttpConnectionManagerParams params = new HttpConnectionManagerParams(); > params.setConnectionTimeout(30000); > params.setSoTimeout(30000); > params.setMaxTotalConnections(500); > params.setDefaultMaxConnectionsPerHost(500); > params.setStaleCheckingEnabled(true); > connectionManager.setParams(params); > httpClient = new HttpClient(connectionManager); > > } > > public String get(String url) throws IOException{ > GetMethod pm = new GetMethod(url); > try { > httpClient.executeMethod(pm); > String response = responseBodyAsString(pm); > return response; > } finally { > pm.releaseConnection(); > } > } > > > > > > -Todd --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
