import org.apache.http.HttpEntity; Import Org.apache.http.HttpResponse; Import org.apache.http.client.HttpClient; Import Org.apache.http.client.methods.HttpGet; Import org.apache.http.impl.client.DefaultHttpClient; Import Org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; Import Org.apache.http.protocol.BasicHttpContext; Import Org.apache.http.protocol.HttpContext; Import Org.apache.http.util.EntityUtils; /** * An example, performs GETs from multiple threads. * */ Public classclientmultithreadedexecution { Public Static voidMain (string[] args) throws Exception {//Create an HttpClient with the Threadsafeclientconnmanager. //This Connection Manager must is used if more than one thread would//Be using the HttpClient. Threadsafeclientconnmanager cm =NewThreadsafeclientconnmanager (); Cm.setmaxtotal ( -); HttpClient HttpClient=Newdefaulthttpclient (cm); Try { //create an array of URIs to perform GETs onstring[] Uristoget = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/", "http://hc.apache.org/httpcomponents-client-ga/", "http://svn.apache.org/viewvc/httpcomponents/" }; //Create a thread for each URIgetthread[] Threads =NewGetthread[uristoget.length]; for(inti =0; i < threads.length; i++) {HttpGet HttpGet=NewHttpGet (Uristoget[i]); Threads[i]=NewGetThread (httpclient, httpget, i +1); } //Start the Threads for(intj =0; J < Threads.length; J + +) {Threads[j].start (); } //Join the Threads for(intj =0; J < Threads.length; J + +) {threads[j].join (); } } finally { //When HttpClient instance is no longer needed,//shut down the connection manager to ensure//immediate deallocation of all system resourcesHttpclient.getconnectionmanager (). Shutdown (); } } /** * A thread that performs a GET. */ Static classGetThread extends Thread {Privatefinal HttpClient HttpClient; Privatefinal HttpContext context; Privatefinal HttpGet HttpGet; PrivateFinalintID; PublicGetThread (HttpClient HttpClient, HttpGet HttpGet,intID) { This. httpClient =httpClient; This. Context =NewBasichttpcontext (); This. HttpGet =HttpGet; This. ID =ID; } /** * Executes the GetMethod and prints some status information. */@Override Public voidrun () {System. out. println (ID +"-About-get something from"+Httpget.geturi ()); Try { //Execute the methodHttpResponse response =Httpclient.execute (httpget, context); System. out. println (ID +"-Get executed"); //get the response body as an array of byteshttpentity entity =response.getentity (); if(Entity! =NULL) { byte[] bytes =Entityutils.tobytearray (entity); System. out. println (ID +" - "+ Bytes.length +"bytes Read"); } } Catch(Exception e) {httpget.abort (); System. out. println (ID +"-Error:"+e); } } } }
Threadsafeclientconnmanager used to support multi-threaded use of HTTP client