壓力測試java實現 原

用了一段時間的Jemter對系統進行壓力測試,感覺不穩定,經常線程上不去,jemter鏈接超時等錯誤,然後自己實現一個壓測,雖然功能比較簡單,但基本測試還是良好。

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 壓力測試
 */
public class PerformanceTest {

    public static void main(String[] src) {
        ArrayBlockingQueue<Runnable> workQueue =new ArrayBlockingQueue<Runnable>(100);
        final ThreadPoolExecutor performenceTestExecutorService = new ThreadPoolExecutor(300, 300, 60, TimeUnit.SECONDS, workQueue);
        final AtomicInteger atomicInteger = new AtomicInteger(1);
        final long startTime = System.currentTimeMillis();
        new Thread() {
            public void run() {
                while (true) {
                    System.out.println("當前隊列大小:"+performenceTestExecutorService.getQueue().size());
                    System.out.println("活動線程數:" + performenceTestExecutorService.getActiveCount());
                    if(performenceTestExecutorService.getQueue().size()<100) {
                        performenceTestExecutorService.execute(new PerformanceThread(atomicInteger, startTime));
                    }
                    else {
                        while(true) {
                            try {
                                Thread.sleep(1000);
                                if(performenceTestExecutorService.getQueue().size()<100) {
                                    break;
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                    }


                }

            }
        }.start();
    }

}
class PerformanceThread extends Thread {

    AtomicInteger atomicInteger;
    long startTime;

    public PerformanceThread(AtomicInteger atomicInteger,long startTime) {
        this.atomicInteger = atomicInteger;
        this.startTime = startTime;

    }

    public void run() {
        System.out.println("開始執行請求");
        RequestResult requestResult = SendHttpRequestUtil.doGet("https://www.test.com");
        if(requestResult.getStatusCode()==200) {
            int completeTaskCount =  atomicInteger.getAndIncrement();
            long endTime = System.currentTimeMillis();
            long takeTime = endTime-startTime;
            double completeTaskCountDouble = Double.parseDouble(String.valueOf(completeTaskCount));
            double takeTimeDouble = Double.parseDouble(String.valueOf(takeTime));
            double performnum = completeTaskCountDouble/takeTimeDouble*1000;
            System.out.println("併發數:" + (int) performnum + "/s"+"成功請求總數:"+completeTaskCountDouble+"總時間:"+takeTimeDouble+"ms");
        }
        //System.out.println(requestResult.getResult());
    }
}

 

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import org.apache.commons.io.IOUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用於發送http請求的工具類
 *
 */

public class SendHttpRequestUtil {

    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;
    private static final int MAX_TIMEOUT = 7000;
    private static final String CODE = "UTF-8";
    private static List<String> encludeList = new ArrayList<String>();
    
    static {
        // 設置連接池
        connMgr = new PoolingHttpClientConnectionManager();
        // 設置連接池大小
        connMgr.setMaxTotal(1000);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

        RequestConfig.Builder configBuilder = RequestConfig.custom();
        // 設置連接超時
        configBuilder.setConnectTimeout(MAX_TIMEOUT);
        // 設置讀取超時
        configBuilder.setSocketTimeout(MAX_TIMEOUT);
        // 設置從連接池獲取連接實例的超時
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
        // 在提交請求之前 測試連接是否可用
        configBuilder.setStaleConnectionCheckEnabled(true);
        requestConfig = configBuilder.build();
         
    }

    /**
     * 填充請求頭參數至get請求中
     *
     * @param httpPost
     * @param headers
     * @return
     */
    private static HttpGet setHeadersToGet(HttpGet httpPost, Map<String, String> headers) {
        if (headers != null && headers.size() != 0) {
            for (String key : headers.keySet()) {
                httpPost.addHeader(key, headers.get(key));
            }
        }
        return httpPost;
    }


    /**
     * 填充請求頭參數至Post請求中
     *
     * @param httpPost
     * @param headers
     * @return
     */
    private static HttpPost setHeadersToPost(HttpPost httpPost, Map<String, String> headers) {
        if (headers != null && headers.size() != 0) {
            for (String key : headers.keySet()) {
                httpPost.addHeader(key, headers.get(key));
            }
        }
        return httpPost;
    }


    /**
     * 填充請求頭參數至Put請求中
     *
     * @param httpPut
     * @param headers
     * @return
     */
    private static HttpPut setHeadersToPut(HttpPut httpPut, Map<String, String> headers) {
        if (headers != null && headers.size() != 0) {
            for (String key : headers.keySet()) {
                httpPut.addHeader(key, headers.get(key));
            }
        }
        return httpPut;
    }


    /**
     * 填充請求體參數至Post請求中
     *
     * @param httpPost
     * @param params
     * @return
     */
    private static HttpPost setParamsToRequest(HttpPost httpPost, Map<String, Object> params) {

        List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            NameValuePair pair = null;
            if (entry.getValue() == null) {
                pair = new BasicNameValuePair(entry.getKey(), null);
            } else {
                pair = new BasicNameValuePair(entry.getKey(), entry
                        .getValue().toString());
            }
            pairList.add(pair);
        }
        httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
        return httpPost;
    }


    /**
     * 發送 GET 請求(HTTP),不帶輸入數據
     *
     * @param url
     * @return
     */
    public static RequestResult doGet(String url) {
        return doGet(url, new HashMap<String, Object>(), new HashMap<String, String>());
    }

    /**
     * 發送 GET 請求(HTTP),K-V形式,無請求頭參數
     *
     * @param url
     * @param params
     * @return
     */
    public static RequestResult doGet(String url, Map<String, Object> params) {
        return doGet(url, params, null);
    }

    /**
     * 發送 GET 請求(HTTP),K-V形式,有請求頭參數
     *
     * @param url     API接口URL
     * @param params  參數map
     * @param headers 請求頭參數
     * @return
     */
    public static RequestResult doGet(String url, Map<String, Object> params, Map<String, String> headers) {
        BasicCookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("test", "test");
        cookie.setVersion(0);
        cookie.setDomain("www.test.com");
        cookie.setPath("/");
        cookieStore.addCookie(cookie);
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultRequestConfig(requestConfig).build();
        HttpGet httpGet = null;
        CloseableHttpResponse response = null;
        RequestResult requestResult = new RequestResult();
        String apiUrl = url;
        StringBuffer param = new StringBuffer();
        int i = 0;
        if (params != null && params.size() > 0) {
            for (String key : params.keySet()) {
                if (i == 0)
                    param.append("?");
                else
                    param.append("&");
                param.append(key).append("=").append(params.get(key));
                i++;
            }
        }
        apiUrl += param;
        String result = null;
        try {
            HttpEntity entity = null;
            httpGet = new HttpGet(apiUrl);
            httpGet = setHeadersToGet(httpGet, headers);
            response = httpClient.execute(httpGet);
            if (response != null) {
                entity = response.getEntity();
            }

            if (entity != null) {
            	InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, "UTF-8");
                requestResult.setResult(result);
                
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            requestResult.setStatusCode(response.getStatusLine().getStatusCode());
            try {
            	response.close();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            
        }
        return requestResult;
    }

    /**
     * 發送 POST 請求(HTTP),不帶輸入數據
     *
     * @param url
     * @return
     */
    public static RequestResult doPost(String url) {
        return doPost(url, new HashMap<String, Object>(), new HashMap<String, String>());
    }

    /**
     * 發送 POST 請求(HTTP),JSON形式,無請求頭參數
     *
     * @param url
     * @param json json對象
     * @return
     */
    public static RequestResult doPost(String url, Object json) {
        return doPost(url, json, null);
    }

    /**
     * 發送 POST 請求(HTTP),K-V形式,無請求頭參數
     *
     * @param url
     * @param params
     * @return
     */
    public static RequestResult doPost(String url, Map<String, Object> params) {
        return doPost(url, params, null);
    }

    /**
     * 發送 POST 請求(HTTP),K-V形式 ,有請求頭參數
     *
     * @param url     API接口URL
     * @param params  參數map
     * @param headers 請求頭參數
     * @return
     */
    public static RequestResult doPost(String url, Map<String, Object> params, Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        RequestResult requestResult = new RequestResult();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;

        try {

            httpPost.setConfig(requestConfig);
            httpPost = setHeadersToPost(httpPost, headers);
            httpPost = setParamsToRequest(httpPost, params);
            response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity entity = response.getEntity();
                httpStr = EntityUtils.toString(entity, "UTF-8");
            }
            requestResult.setResult(httpStr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            requestResult.setStatusCode(response.getStatusLine().getStatusCode());
        }
        return requestResult;
    }

    /**
     * 發送 POST 請求(HTTP),JSON形式,有請求頭參數
     *
     * @param url
     * @param json    json對象
     * @param headers 請求頭參數
     * @return
     */
    public static RequestResult doPost(String url, Object json, Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        RequestResult requestResult = new RequestResult();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;

        try {
            httpPost.setConfig(requestConfig);
            httpPost = setHeadersToPost(httpPost, headers);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解決中文亂碼問題
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity entity = response.getEntity();
                httpStr = EntityUtils.toString(entity, "UTF-8");
            }
            requestResult.setResult(httpStr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            requestResult.setStatusCode(response.getStatusLine().getStatusCode());
        }
        return requestResult;
    }

    /**
     * 發送 SSL POST 請求(HTTPS),無K-V形式參數,無請求頭參數
     *
     * @param url API接口URL
     * @return
     */
    public static RequestResult doPostSSL(String url) {
        return doPostSSL(url, null, null);
    }

    /**
     * 發送 SSL POST 請求(HTTPS),K-V形式,無請求頭參數
     *
     * @param url    API接口URL
     * @param params 參數map
     * @return
     */
    public static RequestResult doPostSSL(String url, Map<String, Object> params) {
        return doPostSSL(url, params, null);
    }

    /**
     * 發送 SSL POST 請求(HTTPS),K-V形式,有請求頭參數
     *
     * @param url     API接口URL
     * @param params  參數map
     * @param headers 請求頭參數
     * @return
     */
    public static RequestResult doPostSSL(String url, Map<String, Object> params, Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
        RequestResult requestResult = new RequestResult();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        String httpStr = null;

        try {
            HttpEntity entity = null;
            httpPost.setConfig(requestConfig);

            httpPost = setHeadersToPost(httpPost, headers);
            httpPost = setParamsToRequest(httpPost, params);
            response = httpClient.execute(httpPost);
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                entity = response.getEntity();
                requestResult.setStatusCode(statusCode);
                if (statusCode != HttpStatus.SC_OK || entity == null) {
                    return requestResult;
                }
            }
            httpStr = EntityUtils.toString(entity, "utf-8");
            requestResult.setResult(httpStr);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return requestResult;
    }

    /**
     * 發送 SSL POST 請求(HTTPS),JSON形式,有請求頭參數
     *
     * @param url  API接口URL
     * @param json JSON對象
     * @return
     */
    public static RequestResult doPostSSL(String url, Object json) {
        return doPostSSL(url, json, null);
    }

    /**
     * 發送 SSL POST 請求(HTTPS),JSON形式,有請求頭參數
     *
     * @param url     API接口URL
     * @param json    JSON對象
     * @param headers 請求頭參數
     * @return
     */
    public static RequestResult doPostSSL(String url, Object json, Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
        RequestResult requestResult = new RequestResult();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        String httpStr = null;

        try {
            HttpEntity entity = null;
            httpPost.setConfig(requestConfig);
            httpPost = setHeadersToPost(httpPost, headers);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解決中文亂碼問題
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                entity = response.getEntity();
                requestResult.setStatusCode(statusCode);
                if (statusCode != HttpStatus.SC_OK || entity == null) {
                    return requestResult;
                }
            }

            httpStr = EntityUtils.toString(entity, "utf-8");
            requestResult.setResult(httpStr);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            requestResult.setStatusCode(response.getStatusLine().getStatusCode());
        }
        return requestResult;
    }

    /**
     * 發送 SSL GET 請求(HTTPs),無參數,無請求頭參數
     *
     * @param url API接口URL
     * @return
     */
    public static RequestResult doGetSSL(String url) {
        return doGetSSL(url, null, null);
    }

    /**
     * 發送 SSL GET 請求(HTTPs),K-V形式,無請求頭參數
     *
     * @param url    API接口URL
     * @param params 參數map
     * @return
     */
    public static RequestResult doGetSSL(String url, Map<String, Object> params) {
        return doGetSSL(url, params, null);
    }

    /**
     * 發送 SSL GET 請求(HTTPs),K-V形式,有請求頭參數
     *
     * @param url     API接口URL
     * @param params  參數map
     * @param headers 請求頭參數
     * @return
     */
    public static RequestResult doGetSSL(String url, Map<String, Object> params, Map<String, String> headers) {

        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
        HttpGet httpGet = null;
        CloseableHttpResponse response = null;
        RequestResult requestResult = new RequestResult();
        String apiUrl = url;
        StringBuffer param = new StringBuffer();
        int i = 0;
        if (params != null && params.size() > 0) {
            for (String key : params.keySet()) {
                if (i == 0)
                    param.append("?");
                else
                    param.append("&");
                param.append(key).append("=").append(params.get(key));
                i++;
            }
        }
        apiUrl += param;
        String result = null;
        try {
            HttpEntity entity = null;
            httpGet = new HttpGet(apiUrl);
            httpGet.setConfig(requestConfig);
            httpGet = setHeadersToGet(httpGet, headers);
            response = httpclient.execute(httpGet);
            if (response != null) {
                entity = response.getEntity();
            }

            if (entity != null) {
                InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, "UTF-8");
                requestResult.setResult(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            requestResult.setStatusCode(response.getStatusLine().getStatusCode());
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return requestResult;
    }


    /**
     * 發送 PUT 請求(HTTP),無參數,無請求頭參數
     *
     * @param url API接口URL
     * @return
     */
    public static RequestResult put(String url) {
        return put(url, null, null);
    }

    /**
     * 發送 PUT 請求(HTTP),K-V形式,無請求頭參數
     *
     * @param url    API接口URL
     * @param params 參數map
     * @return
     */
    public static RequestResult put(String url, Map<String, String> params) {
        return put(url, params, null);
    }

    /**
     * 發送 PUT 請求(HTTP),K-V形式,有請求頭參數
     *
     * @param url     API接口URL
     * @param params  參數map
     * @param headers 請求頭參數
     * @return
     */
    public static RequestResult put(String url, Map<String, String> params, Map<String, String> headers) {
        CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        String responseText = "";
        HttpEntity entity = null;
        RequestResult requestResult = null;
        CloseableHttpResponse response = null;
        String httpStr = null;
        try {
            HttpPut httpPut = new HttpPut(url);
            if (headers != null) {
                Set<String> set = headers.keySet();
                for (String item : set) {
                    String value = headers.get(item);
                    httpPut.addHeader(item, value);
                }
            }
            if (params != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> param : params.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
                    paramList.add(pair);
                }
                httpPut.setEntity(new UrlEncodedFormEntity(paramList, CODE));
            }
            response = client.execute(httpPut);
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                entity = response.getEntity();
                requestResult.setStatusCode(statusCode);
                if (statusCode != HttpStatus.SC_OK || entity == null) {
                    return requestResult;
                }
            }

            httpStr = EntityUtils.toString(entity, "utf-8");
            requestResult.setResult(httpStr);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    EntityUtils.consume(response.getEntity());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return requestResult;
    }


    /**
     * 發送 SSL PUT 請求(HTTP),JSON形式,無請求頭參數
     *
     * @param url  API接口URL
     * @param json JSON對象
     * @return
     */
    public static RequestResult doPut(String url, Object json) {
        return doPut(url, json, null);
    }

    /**
     * 發送 PUT 請求(HTTP),JSON形式,有請求頭參數
     *
     * @param url     API接口URL
     * @param json    JSON對象
     * @param headers 請求頭參數
     * @return
     */
    public static RequestResult doPut(String url, Object json, Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        RequestResult requestResult = new RequestResult();
        HttpPut httpPut = new HttpPut(url);
        CloseableHttpResponse response = null;
        String httpStr = null;

        try {
            HttpEntity entity = null;
            httpPut.setConfig(requestConfig);
            httpPut = setHeadersToPut(httpPut, headers);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解決中文亂碼問題
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPut.setEntity(stringEntity);
            response = httpClient.execute(httpPut);
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                entity = response.getEntity();
                requestResult.setStatusCode(statusCode);
                if (statusCode != HttpStatus.SC_OK || entity == null) {
                    return requestResult;
                }
            }

            httpStr = EntityUtils.toString(entity, "utf-8");
            requestResult.setResult(httpStr);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            requestResult.setStatusCode(response.getStatusLine().getStatusCode());
        }
        return requestResult;
    }

    /**
     * 發送 DELETE 請求(HTTP),無參數
     *
     * @param url API接口URL
     * @return
     */
    public static RequestResult doDelete(String url) {
        return doDelete(url, null, null);
    }

    /**
     * 發送 DELETE 請求(HTTP),K-V形式,無請求頭參數
     *
     * @param url    API接口URL
     * @param params 參數map
     * @return
     */
    public static RequestResult doDelete(String url, Map<String, String> params) {
        return doDelete(url, params, null);
    }

    /**
     * 發送 DELETE 請求(HTTP),K-V形式,有請求頭參數
     *
     * @param url     API接口URL
     * @param params  參數map
     * @param headers 請求頭參數
     * @return
     */
    public static RequestResult doDelete(String url, Map<String, String> params, Map<String, String> headers) {
        CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        String responseText = "";
        HttpEntity entity = null;
        RequestResult requestResult = null;
        CloseableHttpResponse response = null;
        String httpStr = null;
        try {
            HttpDelete httpDelete = new HttpDelete(url);
            if (headers != null) {
                Set<String> set = headers.keySet();
                for (String item : set) {
                    String value = headers.get(item);
                    httpDelete.addHeader(item, value);
                }
            }
            if (params != null) {
                URIBuilder uriBuilder = new URIBuilder(url);
                if (params != null) {
                    for (String key : params.keySet()) {
                        uriBuilder.setParameter(key, params.get(key));
                    }
                }
                URI uri = uriBuilder.build();
                httpDelete.setURI(uri);
            }
            response = client.execute(httpDelete);
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                entity = response.getEntity();
                requestResult.setStatusCode(statusCode);
                if (statusCode != HttpStatus.SC_OK || entity == null) {
                    return requestResult;
                }
            }

            httpStr = EntityUtils.toString(entity, "utf-8");
            requestResult.setResult(httpStr);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    EntityUtils.consume(response.getEntity());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return requestResult;
    }

    /**
     * 創建SSL安全連接
     *
     * @return
     */
    private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
        SSLConnectionSocketFactory sslsf = null;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {


                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

                public void verify(String host, SSLSocket ssl) throws IOException {
                }

                public void verify(String host, X509Certificate cert) throws SSLException {
                }

                public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                }
            });
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        return sslsf;
    }
    
    
    
    public static void main(String[] args) {

	}
}
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.3.2</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
測試結果:
併發數:65/s成功請求總數:2196.0總時間:33646.0ms
開始執行請求
併發數:65/s成功請求總數:2197.0總時間:33675.0ms
開始執行請求
併發數:65/s成功請求總數:2198.0總時間:33696.0ms
開始執行請求
併發數:65/s成功請求總數:2199.0總時間:33704.0ms
開始執行請求
併發數:65/s成功請求總數:2200.0總時間:33722.0ms

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章