接口测试 - httpClient

接口测试 - httpClient

作者: Max.Bai

时间: 2015/09


接口测试 - httpClient

接口测试基础类,借鉴网络资料做部分修改

httpclient4.5.1

代码如下:

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.time.StopWatch;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.ConnectionConfig;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;


/**
 * @author Max.Bai 20150925
 */
public class HttpClientUtils {

    private static final Logger log                 = LogManager.getLogger(HttpClientUtils.class);
    
    private static int          timeOut             = 500;
    private static int          retryCount          = 1;
    private static int          connectionTimeout   = 500;
    private static int          maxHostConnections  = 32;                                     //根据apache work MPM设置此值
    private static int          maxTotalConnections = 512;                                    //同上
    private static String       charsetName         = "UTF-8";

    public static String executeMethod(CloseableHttpClient httpClient, HttpUriRequest method) {

    	String result = "";
        StopWatch watch = new StopWatch();
        CloseableHttpResponse response = null;
        int status = 0;
        try {
            log.info(String.format("Execute method({%s}) begin...", method.getURI()));

            watch.start();
            response = httpClient.execute(method);
            watch.stop();

            status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK) {
            	// Get hold of the response entity
                HttpEntity entity = response.getEntity();

                // If the response does not enclose an entity, there is no need
                // to bother about connection release
                if (entity != null) {

                    log.info(String.format("Response is:{%s}", response));

                    result = EntityUtils.toString(entity);
                }

            } else {
                log.error(String.format("Http request failure! status is {%s}", status));
            }
        } catch (SocketTimeoutException e) {
            log.error("Request time out!");//只关注请求超时,对于其它两类超时,使用通用异常捕获
        } catch (Exception e) {
            log.error("Error occur!", e);
        } finally {
            //method.releaseConnection();
        	try {
				response.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            log.info(String.format("Method {%s},statusCode {%s},consuming {%s} ms", method.getMethod(),
                    status, watch.getTime()));
        }
        return result;
    }

    /**
     * @param uri
     * @param nameValuePairs
     * @return
     */
    public static HttpPost createPostMethod(String uri, List<BasicNameValuePair> nameValuePairs) {
        HttpPost httpPost = new HttpPost(uri);
        
        try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        return httpPost;
    }

    /**
     * @param uri
     * @param nameValuePairs
     * @return
     */
    public static HttpGet createGetMethod(String uri, List<BasicNameValuePair> nameValuePairs) {
    	String url = uri;
		if(nameValuePairs.size()>0) {
			String sParam = "";
			for (NameValuePair p : nameValuePairs) {
				sParam += (p.getName() + "=" + p.getValue() + "&");
			}
			sParam = sParam.substring(0, sParam.length() - 2);
			url = url + "?" + sParam;
		}
    	
    	HttpGet httpget = new HttpGet(url);
        
        return httpget;
    }

    public static CloseableHttpClient createHttpClient() {
    	PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    	ConnectionConfig connectionConfig = ConnectionConfig.custom()
                .setCharset(Consts.UTF_8)
                .build();
    	connManager.setDefaultConnectionConfig(connectionConfig);
    			
    	 RequestConfig defaultRequestConfig = RequestConfig.custom()
    	            .setCookieSpec(CookieSpecs.DEFAULT)
    	            .setExpectContinueEnabled(true)
    	            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
    	            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
	                 .setSocketTimeout(timeOut)
	                 .setConnectTimeout(connectionTimeout)
	                 .setConnectionRequestTimeout(timeOut)
    	            .build();
    	 
    	CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(defaultRequestConfig)
                .setConnectionManager(connManager)
                .build();
    	
    	return httpClient;
    }

    public static void closeHttpClient(CloseableHttpClient httpClient) {
    	try {
    		log.info("Close httpclient ...");
			httpClient.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    public static String doGet(String url, List<BasicNameValuePair> params) {
        return executeMethod(createHttpClient(), createGetMethod(url, params));
    }

    public static String doPost(String url, List<BasicNameValuePair> params) {
        return executeMethod(createHttpClient(), createPostMethod(url, params));
    }

    protected HttpClientUtils() {

    }

    public void setTimeOut(int timeOut) {
        HttpClientUtils.timeOut = timeOut;
    }

    public static int getTimeOut() {
        return timeOut;
    }

    public static int getRetryCount() {
        return retryCount;
    }

    public void setRetryCount(int retryCount) {
        HttpClientUtils.retryCount = retryCount;
    }

    public static int getConnectionTimeout() {
        return connectionTimeout;
    }

    public void setConnectionTimeout(int connectionTimeout) {
        HttpClientUtils.connectionTimeout = connectionTimeout;
    }

    public static int getMaxHostConnections() {
        return maxHostConnections;
    }

    public void setMaxHostConnections(int maxHostConnections) {
        HttpClientUtils.maxHostConnections = maxHostConnections;
    }

    public static int getMaxTotalConnections() {
        return maxTotalConnections;
    }

    public void setMaxTotalConnections(int maxTotalConnections) {
        HttpClientUtils.maxTotalConnections = maxTotalConnections;
    }

    public static String getCharsetName() {
        return charsetName;
    }

    public void setCharsetName(String charsetName) {
        HttpClientUtils.charsetName = charsetName;
    }
}

借鉴

http://blog.csdn.net/fengjia10/article/details/7315279

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值