最近再做接口自动化测试,其中有几个方法比较重要
1.获取http状态码
/** 返回接口状态码
**/
public staticString getHttpCode(String url) {
String code= null;try{
URL u= newURL(url);
URLConnection uc=u.openConnection();
HttpURLConnection huc=(HttpURLConnection)uc;
code= newInteger(huc.getResponseCode()).toString();
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();
}returncode;
}
2.获取json
/** 3个参数
**/
public staticString getJson(String base_url, String para1, String value1, String para2, String value2, String para3, String value3) {
String url= base_url + para1 + "=" + value1 + "&"
+ para2 + "=" + value2 + "&"
+ para3 + "=" +value3;
String result= "";
String code=getHttpCode(url);if(!code.startsWith("2")) {
result= "*******接口的状态码为:"+code+"*******"+url;
}else{
StringBuilder json= newStringBuilder();try{
URL u= newURL(url);
URLConnection uc=u.openConnection();
BufferedReader bd= new BufferedReader(new InputStreamReader(uc.getInputStream(),"UTF-8"));
String s= null;while((s=bd.readLine())!=null) {
json.append(s);
}
bd.close();
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();
}
result=json.toString();
}returnresult;
}
3.获取json中的某个值,如{"a","1"}
public staticString getJsonValue(String json, String name){
String s= null;
JSONObject jobj=JSONObject.fromObject(json);//JSONObject jobj = JSONObject.fromObject("{‘total‘:‘0‘,‘message‘:‘用户编号不能为空‘,‘data‘:‘‘,‘code‘:‘2‘,‘rows‘:‘‘}");
Iterator it =jobj.keys();while(it.hasNext()){
String key=it.next().toString();
String value=jobj.getString(key);if(key.equals(name)) {
s=value.trim();
}
}returns;
}
4.获取双重json中第二维json的某个值,如{"a","1",{"b","1"}}
public staticString getJsonValue(String json,String jdate, String name){
JSONObject jobj=JSONObject.fromObject(json);
JSONObject dataList=jobj.getJSONObject(jdate);
String balance=dataList.getString(name);returnbalance;
}
5.获取json中包含数组中的第N个json,如{"a","1","b","[{"a2","1"},{"b2","1"}]"}
/*获取jsonArray*/
public static String getJsonArray(String json, String arr_name, intindex) {
JSONObject jobj=JSONObject.fromObject(json);
JSONArray childs=jobj.getJSONArray(arr_name);
JSONObject job=childs.getJSONObject(index);returnjob.toString();
}
6.连接数据库
public static ListconnectSqlList(String sql,String userNum, String col) {
String url= "jdbc:mysql://172.16.30.209:3306/a_test";
String name= "gmsd";
Connection con= null;
ResultSet rs= null;
String rssql= null;
List list = new ArrayList();try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con= DriverManager.getConnection(url,name,"dlnu1234");
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(1, userNum);
rs=pst.executeQuery();while(rs.next()) {
rssql=rs.getString(col);
list.add(rssql);
}
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();
}finally{try{
rs.close();
con.close();
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}returnlist;
}
原文:http://www.cnblogs.com/qiaoyeye/p/4730930.html