http 接口测试 java_接口测试 java+httpclient+testng+excel

packagecom.ygsoft.test.api;importjava.io.File;importjava.io.IOException;importjava.nio.charset.Charset;importjava.util.HashMap;importjava.util.Map;importorg.apache.commons.collections.map.StaticBucketMap;import org.apache.http.*;import org.apache.http.client.*;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpDelete;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.client.methods.HttpPut;import org.apache.http.entity.*;importorg.apache.http.entity.StringEntity;importorg.apache.http.entity.mime.HttpMultipartMode;importorg.apache.http.entity.mime.MultipartEntityBuilder;importorg.apache.http.entity.mime.content.FileBody;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.util.EntityUtils;importorg.apache.poi.ss.formula.functions.Column;importorg.openxmlformats.schemas.wordprocessingml.x2006.main.impl.STTabTlcImpl;importorg.testng.log4testng.Logger;importcom.alibaba.fastjson.JSONObject;public class HttpClientUtil extendsParasUtil {final static Logger Log = Logger.getLogger(HttpClientUtil.class);public static intstatusCode;public staticString reponseContent;public staticString Authorization;public staticString token;public static HashMap headers = new HashMap();/*** 不带请求头的get方法封装

*

*@paramurl

*@return返回响应对象

*@throwsClientProtocolException

*@throwsIOException*/

public String get(String url) throwsClientProtocolException, IOException {//创建一个可关闭的HttpClient对象

CloseableHttpClient httpclient =HttpClients.createDefault();//创建一个HttpGet的请求对象

HttpGet httpget = newHttpGet(url);//执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收

Log.info("开始发送get请求...");

CloseableHttpResponse httpResponse=httpclient.execute(httpget);

reponseContent= EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

Log.info("返回内容:" +reponseContent);returnreponseContent;

}/*** 带请求头信息的get方法

*

*@paramurl

*@paramheadermap,键值对形式

*@return返回响应对象

*@throwsClientProtocolException

*@throwsIOException*/

public String get(String url, HashMapheadermap)throwsClientProtocolException, IOException {//创建一个可关闭的HttpClient对象

CloseableHttpClient httpclient =HttpClients.createDefault();//创建一个HttpGet的请求对象

HttpGet httpget = newHttpGet(url);//加载请求头到httpget对象

for (Map.Entryentry : headermap.entrySet()) {

httpget.addHeader(entry.getKey(), entry.getValue());

}//执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收

CloseableHttpResponse httpResponse =httpclient.execute(httpget);

reponseContent= EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

Log.info("返回内容:" +reponseContent);returnreponseContent;

}/*** 封装post方法

*

*@paramurl

*@paramentityString,其实就是设置请求json参数

*@paramheadermap,带请求头

*@return返回响应对象

*@throwsClientProtocolException

*@throwsIOException*/

public static String post(String url, String entityString, HashMapheadermap)throwsClientProtocolException, IOException {//创建一个可关闭的HttpClient对象

CloseableHttpClient httpclient =HttpClients.createDefault();//创建一个HttpPost的请求对象

HttpPost httppost = newHttpPost(url);//设置payload

if (entityString != null) {

httppost.setEntity(newStringEntity(entityString));

}//加载请求头到httppost对象

for (Map.Entryentry : headermap.entrySet()) {

httppost.addHeader(entry.getKey(), entry.getValue());

}//发送post请求

CloseableHttpResponse httpResponse =httpclient.execute(httppost);

statusCode=httpResponse.getStatusLine().getStatusCode();

Log.info("返回状态码:" +statusCode);

reponseContent= EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

Log.info("返回内容:" +reponseContent);returnreponseContent;

}/*** 封装 put请求方法,参数和post方法一样

*

*@paramurl

*@paramentityString,这个主要是设置payload,一般来说就是json串

*@paramheaderMap,带请求的头信息,格式是键值对,所以这里使用hashmap

*@return返回响应对象

*@throwsClientProtocolException

*@throwsIOException*/

public CloseableHttpResponse put(String url, String entityString, HashMapheaderMap)throwsClientProtocolException, IOException {

CloseableHttpClient httpclient=HttpClients.createDefault();

HttpPut httpput= newHttpPut(url);

httpput.setEntity(newStringEntity(entityString));for (Map.Entryentry : headerMap.entrySet()) {

httpput.addHeader(entry.getKey(), entry.getValue());

}//发送put请求

CloseableHttpResponse httpResponse =httpclient.execute(httpput);returnhttpResponse;

}/*** 封装 delete请求方法,参数和get方法一样

*

*@paramurl,

* 接口url完整地址

*@return,返回一个response对象,方便进行得到状态码和json解析动作

*@throwsClientProtocolException

*@throwsIOException*/

public CloseableHttpResponse delete(String url) throwsClientProtocolException, IOException {

CloseableHttpClient httpclient=HttpClients.createDefault();

HttpDelete httpdel= newHttpDelete(url);//发送delete请求

CloseableHttpResponse httpResponse =httpclient.execute(httpdel);returnhttpResponse;

}public static String UploadFile(String url, File file, HashMapheadermap) {

CloseableHttpClient httpClient=HttpClients.createDefault();//每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。

String boundary = "----WebKitFormBoundarya4boZUDstbGAOHbb";try{

String fileName=file.getName();

HttpPost httpPost= newHttpPost(url);//加载请求头到httppost对象

for (Map.Entryentry : headermap.entrySet()) {

httpPost.addHeader(entry.getKey(), entry.getValue());

}

httpPost.addHeader("Content-Type", "multipart/form-data; boundary=" +boundary);

MultipartEntityBuilder builder=MultipartEntityBuilder.create();

builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, fileName);

builder.setCharset(Charset.forName("UTF-8"));

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

builder.setBoundary(boundary);

builder.addPart("multipartFile", newFileBody(file));

builder.addTextBody("filename", fileName, ContentType.create("text/plain", Consts.UTF_8));

HttpEntity entity=builder.build();

httpPost.setEntity(entity);

HttpResponse response=httpClient.execute(httpPost);

reponseContent= EntityUtils.toString(response.getEntity(), "UTF-8");

}catch(IOException e) {

e.printStackTrace();

}catch(Exception e) {

e.printStackTrace();

}finally{try{

httpClient.close();

}catch(IOException e) {

e.printStackTrace();

}

}

System.out.println("reponseContent:" +reponseContent);returnreponseContent;

}public static voidlogin() {

headers.put("Content-Type", "application/json;charset=UTF-8");try{

String response=post(login_url, login_request, headers);

JSONObject jsonObject=JSONObject.parseObject(response);

token= jsonObject.getString("access_token");

Authorization= "bearer " + jsonObject.getString("access_token");

System.out.println("登陆成功\nAuthorization:" +Authorization);

}catch(ClientProtocolException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}public static voidlogin_admin() {

headers.put("Content-Type", "application/json;charset=UTF-8");try{

String response=post(login_url, login_admin, headers);

JSONObject jsonObject=JSONObject.parseObject(response);

token= jsonObject.getString("access_token");

Authorization= "bearer " + jsonObject.getString("access_token");

System.out.println("登陆成功\nAuthorization:" +Authorization);

}catch(ClientProtocolException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}public static voidlogout() {

headers.put("Content-Type", "application/x-www-form-urlencoded");

headers.put("Authorization", Authorization);try{

post(logout_url,null, headers);

System.out.println("退出登陆成功");

}catch(ClientProtocolException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}//返回报文写入excel并格式化单元格

public static void writeResult(String fileName, String sheetName, int row, intstatusCodeColumn,int reponseContentColumn, int resultColumn,intresponseKeyColumn, String excepedReponse,String responseKey) {try{

ExcelUtil.writeData(fileName, sheetName, row, statusCodeColumn, String.valueOf(statusCode),null);

ExcelUtil.writeData(fileName, sheetName, row, reponseContentColumn, reponseContent,null);//如果返回包含預期輸入

if(reponseContent.contains(excepedReponse)) {

ExcelUtil.writeData(fileName, sheetName, row, resultColumn,"pass", "GREEN");

}else{

ExcelUtil.writeData(fileName, sheetName, row, resultColumn,"failed", "RED");

}if (responseKey!=null) {

String value=JsonUtil.getKeyValue(reponseContent, responseKey);

ExcelUtil.writeData(fileName, sheetName, row, responseKeyColumn, value,null);

}

}catch(Exception e) {

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值