標籤:
1.下載org.apache.commons.httpclient.jar檔案。
2.利用HttpClient訪問web網站(url)。
3.利用多線程測試並發數。java.util.concurrent包實現並發。
代碼如下:
1 import java.io.IOException; 2 import java.util.concurrent.ExecutorService; 3 import java.util.concurrent.Executors; 4 import java.util.concurrent.TimeUnit; 5 6 import org.apache.commons.httpclient.HttpClient; 7 import org.apache.commons.httpclient.HttpException; 8 import org.apache.commons.httpclient.HttpMethod; 9 import org.apache.commons.httpclient.methods.GetMethod;10 11 12 13 14 public class Ceshi {15 16 /**17 * @param args18 * @throws IOException 19 * @throws HttpException 20 * @throws InterruptedException 21 */22 public static void main(String[] args) throws HttpException, IOException, InterruptedException {23 ExecutorService service=Executors.newFixedThreadPool(Integer.MAX_VALUE);24 int i = 0;25 for ( i= 0; i < 4000; i++) {26 System.out.println("number " + (i+1) + " starts");27 service.execute(new Runnable() {28 @Override29 public void run() {30 try {31 ceshi();32 } catch (HttpException e) {33 System.out.println("HttpException");34 e.printStackTrace();35 } catch (IOException e) {36 System.out.println("IOException");37 e.printStackTrace();38 }39 }40 });41 System.out.println("number " + (i+1) + " ends");42 }43 44 service.shutdown();45 46 47 service.awaitTermination(300,TimeUnit.SECONDS);48 49 System.out.println("ok");50 51 }52 53 54 private static void ceshi() throws HttpException, IOException{55 HttpClient client = new HttpClient();56 57 client.getHostConfiguration().setHost("9.186.62.58",8080,"http");58 59 HttpMethod method = getGetMethod();//使用POST方式提交資料60 61 client.executeMethod(method);62 63 //列印伺服器返回的狀態64 65 System.out.println(method.getStatusLine());66 67 //列印結果頁面68 69 String response = new String(method.getResponseBodyAsString().getBytes("GB2312"));70 71 //列印返回的資訊72 73 System.out.println(response);74 75 method.releaseConnection(); 76 }77 78 private static HttpMethod getGetMethod(){79 80 return new GetMethod("/BiMaiApp/airdetailpage?cityIDs=1");81 82 } 83 84 }View Code
java小程式檢測web的並發數---HttpClient和util包的concurrent