Java版接口自动化–初稿详解编程语言

一、接口参数的获取:

1.参数通过Excel读取,并将结果写入Excel中

Java版接口自动化--初稿详解编程语言

package org.fanqi.operateExcel; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Map; 
import java.util.TreeMap; 
import org.apache.poi.xssf.usermodel.XSSFCell; 
import org.apache.poi.xssf.usermodel.XSSFSheet; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 
public class OperateExcelUtil { 
/* 
* 读取Excel数据 
*/ 
public List<Map<String, Object>> readExcel(String filename) { 
FileInputStream in; 
XSSFWorkbook workbook = null; 
try { 
in = new FileInputStream(filename); 
workbook = new XSSFWorkbook(in); 
} catch (FileNotFoundException e) { 
e.printStackTrace(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
//获取第一张表 
XSSFSheet sheet = workbook.getSheetAt(0); 
List<Map<String, Object>> listCanshu = new ArrayList<Map<String, Object>>(); 
for(int i=1;i<=sheet.getLastRowNum();i++){ 
Map<String, Object> map = new TreeMap<String, Object>(); 
String  cell0 = sheet.getRow(i).getCell(0).getStringCellValue(); 
String  cell1 = sheet.getRow(i).getCell(1).getStringCellValue(); 
//利用map保存参数 
map.put("canshu1", cell0); 
map.put("canshu2", cell1); 
listCanshu.add(map); 
} 
return listCanshu;  
} 
/* 
* 测试结果写入原Excel 
* result为测试结果(Pass or Failed) 
*/ 
public void writeExcel(String filename,List<String> resultList,int resultRow) { 
XSSFWorkbook workbook = null; 
FileInputStream in = null; 
try { 
in = new FileInputStream(filename); 
workbook = new XSSFWorkbook(in); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
XSSFSheet sheet = workbook.getSheetAt(0); 
int rowSum = sheet.getLastRowNum(); 
XSSFCell cell = null; 
for(int i=1;i<=rowSum;i++){ 
cell = sheet.getRow(i).getCell(resultRow); 
cell.setCellValue(resultList.get(i-1)); 
} 
try { 
workbook.write(new FileOutputStream(filename)); 
} catch (FileNotFoundException e) { 
e.printStackTrace(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
/*创建Excel文件 
*  
public void createExcel() { 
XSSFWorkbook x = new XSSFWorkbook(); 
XSSFFont font1 = x.createFont(); 
font1.setFontHeightInPoints((short) 15); 
font1.setFontName("Pristina"); 
font1.setColor(IndexedColors.GREEN.index); 
//font1.setColor(HSSFColor.YELLOW.index); 
XSSFCellStyle style = x.createCellStyle(); 
style.setFont(font1); 
XSSFSheet sheet = x.createSheet(); 
XSSFRow row0 = sheet.createRow(0); 
row0.createCell(0).setCellValue("姓名"); 
row0.getCell(0).setCellStyle(style); 
row0.createCell(1).setCellValue("性别"); 
row0.getCell(1).setCellStyle(style); 
row0.createCell(2).setCellValue("年龄"); 
row0.getCell(2).setCellStyle(style); 
row0.createCell(3).setCellValue("职位"); 
row0.getCell(3).setCellStyle(style); 
row0.createCell(4).setCellValue("工作年限"); 
row0.getCell(4).setCellStyle(style); 
User u = new User(); 
u.setName("郭大侠"); 
u.setSex("男"); 
u.setAge("30"); 
u.setJob("Java开发"); 
u.setExperience("2"); 
User u1 = new User(); 
u1.setName("陶大婶"); 
u1.setSex("男"); 
u1.setAge("28"); 
u1.setJob("Java开发"); 
u1.setExperience("3"); 
ArrayList<User> arrayList = new ArrayList<User>(); 
arrayList.add(u); 
arrayList.add(u1); 
for(int i=1; i<3; i++){ 
XSSFRow row = sheet.createRow(i); 
row.createCell(0).setCellValue(arrayList.get(i-1).getName()); 
row.createCell(1).setCellValue(arrayList.get(i-1).getSex()); 
row.createCell(2).setCellValue(arrayList.get(i-1).getAge()); 
row.createCell(3).setCellValue(arrayList.get(i-1).getJob()); 
row.createCell(4).setCellValue(arrayList.get(i-1).getExperience()); 
} 
try { 
x.write(new FileOutputStream("E://test.xlsx")); 
} catch (FileNotFoundException e) { 
e.printStackTrace(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
} 
*/ 
public static void main(String[] args) { 
OperateExcelUtil op = new OperateExcelUtil(); 
List<String> resultList = new ArrayList<String>(); 
resultList.add("Failed"); 
resultList.add("Pass"); 
op.writeExcel("E://test.xlsx", resultList, 3); 
} 
}

 

可能需要加验签:sign(MD5)验签

Java版接口自动化--初稿详解编程语言

/** 
* MD5工具类(许总监) 
*  
*/ 
public class MD5Util { 
/** 
* Md5. 
*  
* @param value 
*            the value 
* @return the string 
*/ 
public static String md5(String value) { 
return DigestUtils.md5Hex(value); 
} 
public static String md5New(String value) { 
try { 
MessageDigest md = MessageDigest.getInstance("md5"); 
byte[] e = md.digest(value.getBytes()); 
return toHex(e); 
} catch (NoSuchAlgorithmException e) { 
e.printStackTrace(); 
return value; 
} 
} 
/** 
* To hex. 
*  
* @param bytes 
*            the bytes 
* @return the string 
*/ 
private static String toHex(byte bytes[]) { 
StringBuilder hs = new StringBuilder(); 
String stmp = ""; 
for (int n = 0; n < bytes.length; n++) { 
stmp = Integer.toHexString(bytes[n] & 0xff); 
if (stmp.length() == 1) 
hs.append("0").append(stmp); 
else 
hs.append(stmp); 
} 
return hs.toString(); 
} 
}

 

二、请求报文的组装:

1.组装为JSON格式

Java版接口自动化--初稿详解编程语言

package org.fanqi.operateJSONUtil; 
import java.util.List; 
import java.util.Map; 
import org.json.JSONArray; 
import org.json.JSONObject; 
public class BuildJSON { 
/* 
* 组装成JSON形式 
*/ 
public JSONObject buildJSON(Map mapParameters) { 
JSONObject json = new JSONObject(mapParameters); 
return json;      
} 
/* 
* 组装成JSON形式 
*/ 
public JSONObject buildJSONByString(String str) { 
return new JSONObject(str); 
   } 
/* 
* 组装成JSON形式 
* @parameter list<map> 
*/ 
public JSONArray buildsJSON(List<Map> listCanshu) { 
JSONArray jArray = new JSONArray(); 
for(int i=0;i<listCanshu.size();i++ ){ 
JSONObject json = new JSONObject(listCanshu.get(i)); 
jArray.put(json); 
} 
return jArray;      
} 
}

 

三、请求方法:方式get、post、Hessian

1.get请求方式

Java版接口自动化--初稿详解编程语言

/* 
* get请求方式 
* @author:fanqi 
*/ 
public static String httpGetMethod(String url,Map<Object,Object> map) { 
DefaultHttpClient httpClient = new DefaultHttpClient(); 
Object value; 
Object urlInfo = ""; 
for(Object key : map.keySet()){ 
value = map.get(key); 
urlInfo += key+"="+value+"&"; 
} 
urlInfo = urlInfo.toString().substring(0, urlInfo.toString().length()-1);         
url = url + "?" + urlInfo.toString(); 
HttpGet httpGet = new HttpGet(url); 
HttpResponse httpResponse = null; 
try { 
httpResponse = httpClient.execute(httpGet); 
StringBuilder sb = new StringBuilder(); 
InputStream inputStream = httpResponse.getEntity().getContent(); 
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"GBK")); 
String temp = ""; 
while((temp = br.readLine()) != null){ 
sb.append(temp + "/n"); 
} 
return sb.toString(); 
} catch (IllegalStateException e) { 
e.printStackTrace(); 
} catch (IOException e) { 
e.printStackTrace(); 
}         
return null;         
}

 

2.Post请求方式PostMethod(根据httpclient.jar包的版本不同,用到的方法有差异)

Java版接口自动化--初稿详解编程语言

/* 
* author:fanqi 
*/ 
public String  HttpClientPostMethod(String url,Map map) { 
DefaultHttpClient httpClient = new DefaultHttpClient(); 
HttpPost httpPost = new HttpPost(url); 
InputStream responseStream = null; 
//参数形式为JSON格式 
JSONObject parameter = new JSONObject(map); 
try { 
StringEntity entity = new StringEntity(parameter.toString());//解决中文乱码问题可以加参数"utf-8" 
entity.setContentEncoding("UTF-8");     
entity.setContentType("application/json");  
httpPost.setEntity(entity); 
HttpResponse httpResponse = httpClient.execute(httpPost); 
if(httpResponse.getStatusLine().getStatusCode() == 200){ 
HttpEntity httpEntity = httpResponse.getEntity(); 
responseStream = httpEntity.getContent(); 
BufferedReader br = new BufferedReader(new InputStreamReader(responseStream)); 
StringBuilder sb = new StringBuilder(); 
String temp = ""; 
while((temp = br.readLine()) != null){ 
String str = new String(temp.getBytes(), "UTF-8"); 
sb.append(str + "/n"); 
} 
return sb.toString(); 
} 
} catch (IOException e) { 
e.printStackTrace(); 
} 
return null;         
}

————————————————————————————————————————————————————————

Java版接口自动化--初稿详解编程语言

/* 
* author:xu zong jian 
*/ 
public static String HttpClientPostMethod(String url,String sign,Map<String,String> map){ 
try { 
log.info("HttpClientPostMethod -- url:{}",url); 
HttpClient client = new HttpClient(); 
PostMethod postMethod = new PostMethod(url); 
NameValuePair[] data = new NameValuePair[map.keySet().size()]; 
Iterator it = map.entrySet().iterator(); 
int i = 0; 
while (it.hasNext()) { 
Map.Entry entry = (Entry) it.next(); 
Object key = entry.getKey(); 
Object value = entry.getValue(); 
data[i] = new NameValuePair(key.toString(), value.toString()); 
i++; 
} 
postMethod.setRequestBody(data); 
client.executeMethod(postMethod); 
log.info("HttpClientPostMethod -- status:{} ",postMethod.getStatusCode()); 
if (postMethod.getStatusCode() == HttpStatus.SC_OK) { 
return postMethod.getResponseBodyAsString(); 
} 
} catch (Exception e) { 
log.error("HttpClientPostMethod error", e); 
} 
log.info("HttpClientPostMethod return null"); 
return null; 
}

 

3.Hessian请求:

Hessian是基于Binary –RPC(二进制远程过程调用协议)进行通讯。

Hessian就是把Java对象转变成字节序列,然后通过Http传输到目标服务器上(主机),主机收到这个字节序列后,按照一定的协议标准进行反序列,提交给对应的服务处理。处理完成以后以同样的方式返回数据。

需要:Hessian.jar、 所测接口的API包、请求地址

Java版接口自动化--初稿详解编程语言

/* 
* url为请求地址,包含端口号 
* Response为接口请求返回对象 
* ServerClient为接口中定义的请求客户端类 
*/ 
public Response executes(String url) { 
HessianProxyFactory hpf = new HessianProxyFactory(); 
ServerClient ServerClient = null; 
try { 
ServerClient = (ServerClient) hpf.create(ServerClient.class, url); 
} catch (MalformedURLException e) { 
e.printStackTrace(); 
} 
response = ServerClient.TxnSyncAudit(SyncAuditRequestBo); 
return response; 
}

 

四、返回报文的解析:

1.返回JSON格式的报文

Java版接口自动化--初稿详解编程语言

package org.fanqi.operateJSONUtil; 
import java.util.HashMap; 
import java.util.Iterator; 
import java.util.Map; 
import org.json.JSONObject; 
public class AnalysisJSON { 
/* 
* 解析JSON报文,JSON中不嵌套JSON 
*/ 
public Map analysisJSON1(String responseResult) { 
//去掉{} 
responseResult = responseResult.substring(1, responseResult.length()-1); 
String[] strs = responseResult.split(","); 
@SuppressWarnings("rawtypes") 
Map<String, Object> map = new HashMap<String, Object>(); 
for(int i=0;i<strs.length;i++){ 
String[] str = strs[i].split(":"); 
map.put(str[0], str[1]); 
} 
return map; 
} 
/* 
* 解析JSON报文,JSON中不嵌套JSON 
*/ 
public Map analysisJSON2(String responseResult) { 
JSONObject json = new JSONObject(responseResult); 
Iterator<String> it = json.keys(); 
HashMap<String, Object> map = new HashMap<String, Object>(); 
while(it.hasNext()){ 
String key = it.next(); 
Object value = json.getString(key); 
map.put(key, value); 
} 
return map; 
} 
/* 
* 解析JSON报文,JSON中含有JSON数组 
*/ 
public Map analysisJSONs(String responseResult) { 
JSONObject json = new JSONObject(responseResult); 
Iterator<String> it = json.keys(); 
HashMap<String, Object> map = new HashMap<String, Object>(); 
while(it.hasNext()){ 
String key = it.next(); 
Object value = json.getJSONArray(key); 
map.put(key, value); 
} 
return map; 
}         
}

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/7533.html

(0)
上一篇 2021年7月18日
下一篇 2021年7月18日

相关推荐

发表回复

登录后才能评论