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 args 18 * @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 @Override 29 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 }
时间: 2024-10-10 21:44:15