1 32 33 import org.apache.commons.httpclient.HttpClient; 34 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; 35 import org.apache.commons.httpclient.methods.GetMethod; 36 37 42 public class MultiThreadedExample { 43 44 47 public MultiThreadedExample() { 48 super(); 49 } 50 51 public static void main(String [] args) { 52 53 HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); 57 httpClient.getHostConfiguration().setHost("jakarta.apache.org", 80, "http"); 60 61 String [] urisToGet = { 63 "/", 64 "/commons/", 65 "/commons/httpclient/", 66 "http://cvs.apache.org/viewcvs.cgi/jakarta-commons/httpclient/" 67 }; 68 69 GetThread[] threads = new GetThread[urisToGet.length]; 71 for (int i = 0; i < threads.length; i++) { 72 GetMethod get = new GetMethod(urisToGet[i]); 73 get.setFollowRedirects(true); 74 threads[i] = new GetThread(httpClient, get, i + 1); 75 } 76 77 for (int j = 0; j < threads.length; j++) { 79 threads[j].start(); 80 } 81 82 } 83 84 87 static class GetThread extends Thread { 88 89 private HttpClient httpClient; 90 private GetMethod method; 91 private int id; 92 93 public GetThread(HttpClient httpClient, GetMethod method, int id) { 94 this.httpClient = httpClient; 95 this.method = method; 96 this.id = id; 97 } 98 99 102 public void run() { 103 104 try { 105 106 System.out.println(id + " - about to get something from " + method.getURI()); 107 httpClient.executeMethod(method); 109 110 System.out.println(id + " - get executed"); 111 byte[] bytes = method.getResponseBody(); 113 114 System.out.println(id + " - " + bytes.length + " bytes read"); 115 116 } catch (Exception e) { 117 System.out.println(id + " - error: " + e); 118 } finally { 119 method.releaseConnection(); 121 System.out.println(id + " - connection released"); 122 } 123 } 124 125 } 126 127 } 128 | Popular Tags |