com.api.RestClient Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-autotest-tool Show documentation
Show all versions of java-autotest-tool Show documentation
This is an integration of autotest tools
package com.api;
/**
* Created by zhengyu06 on 2017/9/12
*/
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
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.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.cookie.Cookie;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.testng.Reporter;
import tools.poi.ParamAnalysis;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class RestClient {
private ParamAnalysis pa = null;
private CloseableHttpClient httpClient = null;
private CloseableHttpResponse response = null;
private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(60000).build();
private Map headersMap = new ConcurrentHashMap<>();
private CookieStore cookieStore = new BasicCookieStore();//为了getCookieValueMethod2
private HttpClientContext context = HttpClientContext.create();//for getCookieValueMethod1 only
private List cookieList = null;//for getCookieValueMethod1 only
public RestClient() {
this.httpClient = HttpClients.createDefault(); //定义一个连接器
}
public RestClient(String paramFilePath, String sheetName) {
this.httpClient = HttpClients.createDefault(); //定义一个连接器
this.pa = new ParamAnalysis(paramFilePath, sheetName);
}
private String doGetRequest(int rowNum) {
List params = pa.getParamList(rowNum);
String paramString = URLEncodedUtils.format(params, "UTF-8");
Reporter.log("paramString is: "+paramString, true);//已经是userId=29297901的格式了。
String url = "http://" + pa.getHostName(rowNum) + pa.getUri(rowNum) + "?" + paramString;
Reporter.log("URL is: "+url, true);
HttpGet httpGet = new HttpGet(url); //入参url可以使URI类型也可以是String类型。
Reporter.log("Request Line is: "+httpGet.getRequestLine());
try {
this.response = this.httpClient.execute(httpGet);
} catch (ClientProtocolException e1) {
Reporter.log(e1.getMessage(),true);
e1.printStackTrace();
} catch (IOException e1) {
Reporter.log(e1.getMessage(),true);
e1.printStackTrace();
}
int statusCode = this.response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Reporter.log("Method failed:" + response.getStatusLine().toString());
}else{
Reporter.log("Method succeeded:" + response.getStatusLine().toString());
}
HttpEntity responseEntity = this.response.getEntity();
String resultString = this.getResultMethod1(responseEntity);
Reporter.log("GET请求"+url+"后返回的内容:\n" + resultString);
return resultString;
}
protected String getResultMethod1(HttpEntity entity) {
/*下方为获取响应*/
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
StringBuilder jsonStr = new StringBuilder();
try {
is = entity.getContent();
isr = new InputStreamReader(is, "UTF-8");
br = new BufferedReader(isr);//new BufferedReader(isr, 8 * 1024);
String line = "";
while ((line = br.readLine()) != null) {
jsonStr.append(line);
}//while循环获取整个response的StringBuilder
// 其功能就是关闭HttpEntity是的流,如果手动关闭了InputStream instream = entity.getContent();这个流,也可以不调用这个方法。
EntityUtils.consume(entity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(br!=null)
br.close();
if(isr!=null)
isr.close();
if(is!=null)
is.close();
}catch(IOException e) {
e.printStackTrace();
}
}
return jsonStr.toString();
}
protected String getResultMethod2(HttpEntity entity) {
String jsonStr = "";
try {
jsonStr = EntityUtils.toString(entity, "utf-8");//此方法会关闭entity对应的流,后续无法再使用流解析entity。
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonStr;
}
private String doPostRequest(int rowNum) {
String url = "http://"+pa.getHostName(rowNum)+pa.getUri(rowNum);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("User-Agent", "Chrome");
httpPost.setHeader("Referer", pa.getHostName(rowNum));
List params = pa.getParamList(rowNum);
try {
HttpEntity uriEncodedFormEntity = new UrlEncodedFormEntity(params, "UTF-8");//入参为一个List,同时转为UTF-8,UrlEncodedFormEntity继承自HttpEntity
httpPost.setEntity(uriEncodedFormEntity); //UrlEncodedFormEntity类创建的对象可以模拟传统的HTML表单传送POST请求中的参数
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Reporter.log("Request Line is: "+httpPost.getRequestLine());
try {
this.response = this.httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int statusCode = this.response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Reporter.log("Method failed:" + response.getStatusLine().toString());
}else{
Reporter.log("Method succeeded:" + response.getStatusLine().toString());
}
HttpEntity responseEntity = this.response.getEntity();
String resultString = this.getResultMethod2(responseEntity);
Reporter.log("POST请求"+url+"后返回的内容:\n" + resultString);//此句和下面一行一模一样。
Reporter.log("第一条cookies是" + this.response.getFirstHeader("set-cookie"));
Reporter.log("最后一条cookies是" + this.response.getLastHeader("set-cookie"));
Header[] hs = this.response.getHeaders("Set-Cookie");
Reporter.log("cookies的数量是" + hs.length);
return resultString;
}
private String doJsonPostRequest(int rowNum){
List params = pa.getParamList(rowNum);
String paramString = URLEncodedUtils.format(params, "UTF-8");
/*正常application/json格式入参写在body中,
只是我们这次Json格式的请求同时要求把userId以@RequestParam形式传入,所以需要在url加以类似Get请求的传参方式
所以才需要上面两行及下面一行的(?+paramString)*/
String url = "http://"+pa.getHostName(rowNum)+pa.getUri(rowNum)+"?"+paramString;
//下面一行是获取JSON入参,在入参Excel的另一个字段中。
String jsonParamString = pa.getJsonParam(rowNum);
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-type","application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
HttpEntity stringEntity = new StringEntity(jsonParamString, Charset.forName("UTF-8"));
httpPost.setEntity(stringEntity);
try {
this.response = this.httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
int statusCode = this.response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Reporter.log("Method failed:" + response.getStatusLine().toString(), true);
}else{
Reporter.log("Method succeeded:" + response.getStatusLine().toString(), true);
}
HttpEntity responseEntity = this.response.getEntity();
String resultString = this.getResultMethod2(responseEntity);//resultString is in Json.
Reporter.log("POST请求"+url+"后返回的内容:\n" + resultString, true);
return resultString;
}
/*供外部调用时候进行设置使用。*/
public void setRequestHeaders(Map map){
this.headersMap = map;
}
/*供内部在发送请求时从私有成员headerMap中获取内容放入Request的header中。*/
private void setCustomerizedHeaders(HttpRequestBase method){
String value = "";
if (this.headersMap.size() > 0){
Set keySet = this.headersMap.keySet();
for (String key : keySet) {
value = this.headersMap.get(key);
method.setHeader(key, value);
Reporter.log("设置Header: "+key+"="+value,true);
}
}else
Reporter.log("没有额外进行Header参数设置", true);
}
public String getCookieValueMethod1(String key){
Reporter.log("getCookieValueMethod2 method was called.", true);
String value = "";
boolean flag = false;
if (!this.cookieList.isEmpty()){
this.cookieList.forEach(System.out::println);
for (Cookie cookie : cookieList){
if (cookie.getName().equalsIgnoreCase(key)){
flag = true;//说明有匹配的Cookie Name
value = cookie.getValue()==null?"":cookie.getValue();
Reporter.log("Cookie "+cookie.getName()+" 的值为 "+value, true);
break;
}
}
if (!flag) //说明没有匹配的Cookie Name
Reporter.log("Cookies列表中没有 "+key+" 这个Cookie Name", true);
}else
Reporter.log("一个Cookie都没有。", true);
return value;
}
/*可以只使用cookieStore,且在初始化httpClient对象时传入即可。这样可以不需要context和cookieList对象。*/
public String getCookieValueMethod2(String key){
Reporter.log("getCookieValueMethod2 method was called.", true);
Cookie cookie = null;
String value = "";
List list = this.cookieStore.getCookies();
int size = list.size();
if (size > 0){
list.forEach(System.out::println);
for (int i=0; i params = pa.getParamList(rowNum);
String paramString = URLEncodedUtils.format(params, "UTF-8");
Reporter.log("paramString is: "+paramString, true); //已经是userId=29297901的格式了。
String url = pa.getHostName(rowNum) + pa.getUri(rowNum) + "?" + paramString;
Reporter.log("URL is: "+url, true);
/*下面一行方法分析HostName来判断是Http还是Https*/
this.httpOrHttps(url);//用来创建HttpClient对象。
HttpGet httpGet = new HttpGet(url);//入参url可以使URI类型也可以是String类型。
this.setCustomerizedHeaders(httpGet);//如果this.headersMap的size大于0,则向HttpGet的Header中设置个性化headers
Reporter.log("Request Line is: "+httpGet.getRequestLine(), true);
try {
this.response = this.httpClient.execute(httpGet,this.context);
this.cookieList = this.context.getCookieStore().getCookies();//for getCookieValueMethod1 only
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
int statusCode = this.response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Reporter.log("Method failed:" + response.getStatusLine().toString(), true);
}else{
Reporter.log("Method succeeded:" + response.getStatusLine().toString(), true);
}
HttpEntity responseEntity = this.response.getEntity();
String resultString = this.getResultMethod1(responseEntity);
Reporter.log("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆", true);
Reporter.log("GET请求 "+url+"\n响应内容为:\n" + resultString, true);
Reporter.log("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆", true);
return resultString;
}
protected String doPostRequestNew(int rowNum) {
Reporter.log("doPostRequestNew function was called.");
String url = pa.getHostName(rowNum)+pa.getUri(rowNum);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("User-Agent", "Chrome");
httpPost.setHeader("Referer", pa.getHostName(rowNum));
this.setCustomerizedHeaders(httpPost);//如果this.headersMap的size大于0,则向HttpPost的Header中设置个性化的headers
List params = pa.getParamList(rowNum);
try {
HttpEntity uriEncodedFormEntity = new UrlEncodedFormEntity(params, "UTF-8");//入参为一个List,同时转为UTF-8,UrlEncodedFormEntity继承自HttpEntity
httpPost.setEntity(uriEncodedFormEntity); //UrlEncodedFormEntity类创建的对象可以模拟传统的HTML表单传送POST请求中的参数
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Reporter.log("Request Line is: "+httpPost.getRequestLine(), true);
/*下面一行方法分析HostName来判断是Http还是Https*/
this.httpOrHttps(url);
try {
this.response = this.httpClient.execute(httpPost, this.context);
this.cookieList = this.context.getCookieStore().getCookies();//for getCookieValueMethod1 only
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int statusCode = this.response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Reporter.log("Method failed:" + response.getStatusLine().toString(), true);
}else{
Reporter.log("Method succeeded:" + response.getStatusLine().toString(), true);
}
HttpEntity responseEntity = this.response.getEntity();
String resultString = this.getResultMethod2(responseEntity);
Reporter.log("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆", true);
Reporter.log("POST请求 "+url+"\n响应内容为:\n" + resultString, true);
Reporter.log("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆", true);
Reporter.log("第一条cookies是" + this.response.getFirstHeader("set-cookie"));
Reporter.log("最后一条cookies是" + this.response.getLastHeader("set-cookie"));
Header[] hs = this.response.getHeaders("Set-Cookie");
Reporter.log("cookies的数量是" + hs.length);
return resultString;
}
protected String doJsonPostRequestNew(int rowNum){
Reporter.log("doJsonPostRequestNew function was called.");
List params = pa.getParamList(rowNum);
String paramString = URLEncodedUtils.format(params, "UTF-8");
/*正常application/json格式入参写在body中,
只是我们这次Json格式的请求同时要求把userId以@RequestParam形式传入,所以需要在url加以类似Get请求的传参方式
所以才需要上面两行及下面一行的(?+paramString)*/
String url = pa.getHostName(rowNum)+pa.getUri(rowNum)+"?"+paramString;
//下面一行是获取JSON入参,在入参Excel的另一个字段中。
String jsonParamString = pa.getJsonParam(rowNum);
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-type","application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
this.setCustomerizedHeaders(httpPost);//如果this.headersMap的size大于0,则向HttpPost的Header中设置个性化的headers
HttpEntity stringEntity = new StringEntity(jsonParamString, Charset.forName("UTF-8"));
httpPost.setEntity(stringEntity);
/*下面一行方法分析HostName来判断是Http还是Https*/
this.httpOrHttps(url);
try {
this.response = this.httpClient.execute(httpPost,this.context);
this.cookieList = this.context.getCookieStore().getCookies();//for getCookieValueMethod1 only
} catch (IOException e) {
e.printStackTrace();
}
int statusCode = this.response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Reporter.log("Method failed:" + response.getStatusLine().toString(), true);
}else{
Reporter.log("Method succeeded:" + response.getStatusLine().toString(), true);
}
HttpEntity responseEntity = this.response.getEntity();
String resultString = this.getResultMethod2(responseEntity);//resultString is in Json.
Reporter.log("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆", true);
Reporter.log("POST请求 "+url+"\n响应内容为:\n" + resultString, true);
Reporter.log("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆", true);
return resultString;
}
public String doRequest(int rowNum) {
String responseString = "";
String caseName = pa.getCaseName(rowNum-1);
Reporter.log("****************** Case: "+ caseName +" ******************", true);
String method = pa.getMethod(rowNum-1);
if(method.toUpperCase().contentEquals("GET"))
responseString = this.doGetRequestNew(rowNum-1);
else if(method.toUpperCase().contentEquals("POST"))
responseString = this.doPostRequestNew(rowNum-1);
else if (method.toUpperCase().contentEquals("JSON"))
responseString = this.doJsonPostRequestNew(rowNum-1);
else
Reporter.log("Your Method is not correct, please check your data source.", true);
Reporter.log("****************** ******************** ******************", true);
return responseString;
}
public void httpOrHttps(String url){
/*下面分析HostName来判断是Http还是Https*/
if (url.startsWith("http")){
this.httpClient = HttpClients.custom().setDefaultCookieStore(this.cookieStore).setDefaultRequestConfig(requestConfig).build();//定义一个Http连接器
}else if (url.startsWith("https")){
this.httpClient = HttpClients.custom().setSSLSocketFactory((LayeredConnectionSocketFactory)getSSLSocketFactory()).setDefaultCookieStore(this.cookieStore).setDefaultRequestConfig(requestConfig).build();
}else{
Reporter.log("您输入的HostName不正确,请重新输入。", true);
}
}
private static SSLSocketFactory getSSLSocketFactory() {
TrustManager[] tm = {new MyX509TrustManager()};
//创建SSLContext
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
//初始化
if (sslContext != null){
try {
sslContext.init(null, tm, new java.security.SecureRandom());
} catch (KeyManagementException e) {
e.printStackTrace();
}
//获取SSLSocketFactory对象
return sslContext.getSocketFactory();
}else{
return null;
}
}
//为了能够在执行中动态获取之前请求结果作为下一个请求的参数而设置。需在设置NameValuePair之前调用。
public void setKeyValueParam(int rowNum, String name, String value){
this.pa.setNewParam(rowNum-1, name, value);
}
public String getMeiTuanOTPMessage(String url, String mobileNo){
String resultString = "";
String jsonParamString = "{\n" +
" \"mobile\" : \""+ mobileNo +"\"\n" +
"}";
Reporter.log("JSON参数为:"+jsonParamString, true);
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-type","application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
HttpEntity stringEntity = new StringEntity(jsonParamString, Charset.forName("UTF-8"));
httpPost.setEntity(stringEntity);
/*下面一行方法分析HostName来判断是Http还是Https*/
this.httpOrHttps(url);
try {
this.response = this.httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
int statusCode = this.response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Reporter.log("Method failed:" + response.getStatusLine().toString(), true);
}else{
Reporter.log("Method succeeded:" + response.getStatusLine().toString(), true);
}
HttpEntity responseEntity = this.response.getEntity();
resultString = this.getResultMethod2(responseEntity);//resultString is in Json.
Reporter.log("POST请求"+url+"后返回的内容:\n" + resultString, true);
return resultString;
}
public ParamAnalysis getParamAnalysis(){
return this.pa;
}
public String getCellValue(int rowNum, String fieldName){
return this.pa.getCellValueByName(rowNum-1, fieldName);
}
/*脱离Excel,直接发送JSON入参格式的Post请求*/
public String sendDirectJsonPostRequest(String requestUrl, String jsonParamString){
String resultString = "";
Reporter.log("JSON参数为:"+jsonParamString, true);
HttpPost httpPost = new HttpPost(requestUrl);
httpPost.addHeader("Content-type","application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
this.setCustomerizedHeaders(httpPost);//如果this.headersMap的size大于0,则向HttpPost的Header中设置个性化的headers
HttpEntity stringEntity = new StringEntity(jsonParamString, Charset.forName("UTF-8"));
httpPost.setEntity(stringEntity);
/*下面一行方法分析HostName来判断是Http还是Https*/
this.httpOrHttps(requestUrl);
try {
this.response = this.httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
int statusCode = this.response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Reporter.log("Method failed:" + response.getStatusLine().toString(), true);
}else{
Reporter.log("Method succeeded:" + response.getStatusLine().toString(), true);
}
HttpEntity responseEntity = this.response.getEntity();
resultString = this.getResultMethod2(responseEntity);//resultString is in Json.
Reporter.log("POST请求"+requestUrl+"后返回的内容:\n" + resultString, true);
return resultString;
}
/*脱离Excel,直接发送表单格式入参的Post请求*/
public String sendDirectHttpPostRequest(String hostUrl, String requestUri, Map paramsMap) {
Reporter.log("sendDirectHttpPostRequest function was called.");
String url = hostUrl+requestUri;
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("User-Agent", "Chrome");
httpPost.setHeader("Referer", hostUrl);
this.setCustomerizedHeaders(httpPost);//如果this.headersMap的size大于0,则向HttpPost的Header中设置个性化的headers
/*从Map中获取表单格式的Post请求入参。*/
List params = new ArrayList<>();
for(Map.Entry entry:paramsMap.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try {
HttpEntity uriEncodedFormEntity = new UrlEncodedFormEntity(params, "UTF-8");//入参为一个List,同时转为UTF-8,UrlEncodedFormEntity继承自HttpEntity
httpPost.setEntity(uriEncodedFormEntity); //UrlEncodedFormEntity类创建的对象可以模拟传统的HTML表单传送POST请求中的参数
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Reporter.log("Request Line is: "+httpPost.getRequestLine(), true);
/*下面一行方法分析HostName来判断是Http还是Https*/
this.httpOrHttps(url);//用来初始化不同的this.httpClient实例。
try {
this.response = this.httpClient.execute(httpPost, this.context);
this.cookieList = this.context.getCookieStore().getCookies();//for getCookieValueMethod1 only
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int statusCode = this.response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Reporter.log("Method failed:" + response.getStatusLine().toString(), true);
}else{
Reporter.log("Method succeeded:" + response.getStatusLine().toString(), true);
}
HttpEntity responseEntity = this.response.getEntity();
String resultString = this.getResultMethod2(responseEntity);
Reporter.log("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆", true);
Reporter.log("POST请求 "+url+"\n响应内容为:\n" + resultString, true);
Reporter.log("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆", true);
Reporter.log("第一条cookies是" + this.response.getFirstHeader("set-cookie"));
Reporter.log("最后一条cookies是" + this.response.getLastHeader("set-cookie"));
Header[] hs = this.response.getHeaders("Set-Cookie");
Reporter.log("cookies的数量是" + hs.length);
return resultString;
}
/*脱离Excel,直接发送Get请求*/
public String sendDirectHttpGetRequest(String requestUrl, Map paramsMap) {
Reporter.log("sendDirectHttpGetRequest function was called.");
/*从Map中获取表单格式的Post请求入参。*/
List params = new ArrayList<>();
for(Map.Entry entry:paramsMap.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
String paramString = URLEncodedUtils.format(params, "UTF-8");
Reporter.log("paramString is: "+paramString, true); //已经是userId=29297901的格式了。
String url = requestUrl + "?" + paramString;//拼成完整的Get请求地址。
Reporter.log("URL is: "+url, true);
/*下面一行方法分析HostName来判断是Http还是Https*/
this.httpOrHttps(url);//用来创建HttpClient对象。
HttpGet httpGet = new HttpGet(url);//入参url可以使URI类型也可以是String类型。
this.setCustomerizedHeaders(httpGet);//如果this.headersMap的size大于0,则向HttpGet的Header中设置个性化headers
Reporter.log("Request Line is: "+httpGet.getRequestLine(), true);
try {
this.response = this.httpClient.execute(httpGet,this.context);
this.cookieList = this.context.getCookieStore().getCookies();//for getCookieValueMethod1 only
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
int statusCode = this.response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Reporter.log("Method failed:" + response.getStatusLine().toString(), true);
}else{
Reporter.log("Method succeeded:" + response.getStatusLine().toString(), true);
}
HttpEntity responseEntity = this.response.getEntity();
String resultString = this.getResultMethod1(responseEntity);
Reporter.log("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆", true);
Reporter.log("GET请求 "+url+"\n响应内容为:\n" + resultString, true);
Reporter.log("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆", true);
return resultString;
}
/*脱离Excel,直接发送Get请求*/
public String sendDirectHttpGetRequest(String entireUrl) {
Reporter.log("sendDirectHttpGetRequest function was called.");
Reporter.log("URL is: "+entireUrl, true);
/*下面一行方法分析HostName来判断是Http还是Https*/
this.httpOrHttps(entireUrl);//用来创建HttpClient对象。
HttpGet httpGet = new HttpGet(entireUrl);//入参url可以是URI类型也可以是String类型。
this.setCustomerizedHeaders(httpGet);//如果this.headersMap的size大于0,则向HttpGet的Header中设置个性化headers
Reporter.log("Request Line is: "+httpGet.getRequestLine(), true);
try {
this.response = this.httpClient.execute(httpGet,this.context);
this.cookieList = this.context.getCookieStore().getCookies();//for getCookieValueMethod1 only
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
int statusCode = this.response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Reporter.log("Method failed:" + response.getStatusLine().toString(), true);
}else{
Reporter.log("Method succeeded:" + response.getStatusLine().toString(), true);
}
HttpEntity responseEntity = this.response.getEntity();
String resultString = this.getResultMethod1(responseEntity);
Reporter.log("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆", true);
Reporter.log("GET请求 "+entireUrl+"\n响应内容为:\n" + resultString, true);
Reporter.log("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆", true);
return resultString;
}
public void tearDown() {
try {
if(this.response!=null)
this.response.close();
if(this.httpClient!=null)
this.httpClient.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}