Java多线程请求

好久没有更新代码了,最近比较忙,找了个自己最近在用的代码贴上来。中间主要使用了代理和代码改host2种方式的压测,如有需要自取,需要httpclient包。

时间有限,日后再多做处理和更新....

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class test {
    public static long totalCost = 0;
    public static ArrayList<Long> MM = new ArrayList<Long>();
    public static int error=0;
    public static void main(String[] args) throws RemoteException, InterruptedException, IOException {
        int threadCount = Integer.parseInt(args[0]);
        int times = Integer.parseInt(args[1]);
//        int threadCount=1;
//        int times=1;
        File f1=new File("./line.txt");
//        File f2=new File("./report.txt");
//        FileWriter writer = null;
//        writer = new FileWriter(f2,true);
//        BufferedWriter bw = new BufferedWriter(writer);
        FileReader reader = new FileReader(f1);        
        BufferedReader br = new BufferedReader(reader);
        String line="";
        String host="";
        ArrayList<String> al=new ArrayList<String>();
        host="192.168.211.34";
        while((line=br.readLine())!=null){
            line="http://192.168.211.34"+line;
            al.add(line);
        }
        reader.close();
        int size=al.size();
        Random rnd = new Random();
        ExecutorService p = Executors.newFixedThreadPool(threadCount);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");// 设置日期格式
        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        long start=System.currentTimeMillis();
        String l=null;
            for(int j=0;j<threadCount;j++){
//                int p1=rnd.nextInt(size);
//                l=(java.lang.String) al.get(p1);
                l="http://192.168.211.36/sst/Tnpsc%2BIi%2Bvi%2Brecruitment%2Bapplication%2Btnpscexams/";
                p.execute(new thread(l,host,80,times));
//                System.out.println(l);
            }
        while (p.isTerminated() == false){
            p.shutdown();
//            total=System.currentTimeMillis() - start;
        }
        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        long tatal=System.currentTimeMillis();
        System.out.println(l);
//        bw.write("total: "+totalCost+"ms");
//        bw.newLine();
//        bw.flush();
//        bw.write("avg: "+(totalCost/threadCount)+"ms");
//        bw.newLine();
//        bw.flush();
//        bw.close();
//        System.out.println(MM.size());
        System.out.println("total: "+(tatal-start)+"ms");
        System.out.println("avg: "+(totalCost/threadCount/times)+"ms");
        System.out.println("Error:"+error);
        if(MM.size()>1){
            Collections.sort(MM);
            System.out.println("MAX:"+MM.get(MM.size()-1));
            System.out.println("MIN:"+MM.get(0));
        }
    }
}
import java.io.FileNotFoundException;
import java.io.IOException;


public class thread extends Thread {
    String url = "";
    String host ="";
    int port=80;
    int times=0;
    
    public thread(java.lang.String l, java.lang.String string, int i,int t) {
        // TODO Auto-generated constructor stub
        this.url = l;
        this.host=string;
        this.port=i;
        this.times=t;
    }
    
    public void run(){
        for(int i=0;i<times;i++){
            
            UseClient a1=new UseClient();
    //        SocketClient a1=new SocketClient();
            try {
                a1.Client(url,host, port);
    //            a1.socket();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                System.out.println(url+":/t"+e.getMessage());
            } catch (RuntimeException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}
import java.io.IOException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class UseClient {

    // public static void main(String[] args) throws RemoteException,
    // InterruptedException, IOException {
    // UseClient client = new UseClient();
    // client.test1();
    // }
    //
    // public void test1() throws IllegalStateException, IOException {
    // HttpClient client = new DefaultHttpClient();
    // HttpGet request = new HttpGet("http://216.34.207.210/servers-storage/");
    // request.setHeader("Host", "staging.internetcorkboard.com");
    // HttpResponse response = client.execute(request);
    // // Get the response
    // BufferedReader rd = new BufferedReader(new InputStreamReader(response
    // .getEntity().getContent()));
    //
    // String line = "";
    // while ((line = rd.readLine()) != null) {
    // System.out.println(line);
    // }
    //
    // }

    public void Client(String Url, String host, int port)
            throws IllegalStateException, IOException {
        long avg = 0;
        long start = 0;
        // HttpClient client = new DefaultHttpClient();
        // 代理主机ip,int port 代理端口
        // HttpHost proxy = new HttpHost("216.34.207.199", port);
        // HttpHost proxy=new HttpHost("216.34.207.210",port);
        // 设置代理主机.
        // client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
        // get方式连接
        // HttpGet get =new HttpGet(Url);
        // HttpGet get = new HttpGet("http://216.34.207.210/");
        // HttpGet get = new HttpGet("http://baidu.com/");
        // System.out.println(Url);
        // HttpParams params = get.getParams();
        // HttpConnectionParams.setConnectionTimeout(params, 5000);
        // HttpConnectionParams.setSoTimeout(params, 10000);
        //
        // get.getParams().setParameter("http.virtual-host",
        // "staging.internetcorkboard.com");
        // get.getParams().setParameter("http.useragent", "Custom Browser");

        // HttpGet get = new
        // HttpGet("http://staging.internetcorkboard.com/sst/commerce/");
        HttpClient client = new DefaultHttpClient();

        // "http://216.34.207.210/servers-storage/"
        java.io.InputStream instream = null;
        try {
            HttpGet request = new HttpGet(Url);
            //设置不显示cookie warning
            HttpParams params = request.getParams();
            client.getParams().setParameter(ClientPNames.COOKIE_POLICY,
                    CookiePolicy.IGNORE_COOKIES);
            HttpConnectionParams.setConnectionTimeout(params, 120000);
            HttpConnectionParams.setSoTimeout(params, 1200000);
            request.setHeader("Host", "staging.internetcorkboard.com");
            
            start=System.currentTimeMillis();
            client.execute(request);
//            HttpResponse response = client.execute(request);
//            instream = response.getEntity().getContent();
//            // Get the response
//
//            BufferedReader rd = new BufferedReader(new InputStreamReader(
//                    response.getEntity().getContent()));
//
//            String line = "";
//            while ((line = rd.readLine()) != null) {
//                // System.out.println(line);
//            }
            avg = System.currentTimeMillis() - start;
        } catch (Exception e) {
            e.printStackTrace();
            avg = 0;
            test.error++;
        } finally {
            if (instream != null)
                instream.close();
        }
        client.getConnectionManager().shutdown();
        if (avg != 0) {
            test.MM.add(avg);
        }
        // if(avg>300){
        // System.out.println(avg+":"+Url+"   "+r);
        // }
        test.totalCost = test.totalCost + avg;
    }
}

 

posted on 2013-04-16 14:39  IT Ⅳ  阅读(418)  评论(0编辑  收藏  举报

导航