接口测试 - httpClient
来源:互联网 发布:wow 国服 mac 编辑:程序博客网 时间:2024/05/01 18:34
接口测试 - 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 blocke.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 blocke.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 blocke.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
0 0
- testNG+httpclient接口测试
- 接口测试 - httpClient
- 接口测试之HttpClient
- HttpClient天气接口测试
- HttpClient之接口测试
- HttpClient测试接口Test
- 使用HttpClient实现接口测试
- 使用httpClient进行接口测试
- 接口测试及httpclient深入
- 接口测试及httpclient深入
- HttpClient接口测试问题汇总
- httpclient自己写接口性能测试脚本
- 使用HttpClient进行远程接口测试
- 使用HttpClient测试SpringMVC的接口
- Excel+Httpclient,数据驱动接口自动化测试
- HttpClient +Testng(1)进行接口测试入门
- Url接口测试:HttpClient模拟登录效果
- 【接口测试】:HttpClient Post 和 Get 请求
- struts2中的各种各样的内建校验器的小例子
- Intellij IDEA如何使用Maven Tomcat Plugin运行web项目
- onkey事件在return前焦点切换,onkey事件的变化
- MarkDown
- [IOS]'Project Name' was compiled with optimization
- 接口测试 - httpClient
- OpenGL3.0教程
- 位操作_求二进制中1的个数
- iOS多线程编程之NSThread的使用
- 故障排除(一)
- 看
- 研读:AdAttester Secure Online Advertisement Attestation on Mobile Devices Using TrustZone
- Struts对MVC的实现流程
- 简单的通讯录