接口返回值結果轉換成JSON,具體的方法如下:
public static String GetJsonValue(String result,int index,String key){ int indexloc,indexkey; String newstr; indexloc=result.indexOf("["); indexkey=result.indexOf(key); //判斷Data域的內容 if (( indexloc>indexkey || indexloc==-1) & index==0){ JSONObject jsonObj = JSONObject.fromObject(result); return jsonObj.getString(key); } else{ newstr=GetNPro(result,index); return GetJsonValue(newstr,0,key); } } public static String GetNPro(String str,int n){ Matcher slashMatcher = Pattern.compile("\\{").matcher(str); int mIdx = 0; while(slashMatcher.find()) { if(mIdx ==n){ break; } mIdx++; } str=str.substring(slashMatcher.start(),str.length()); return str.substring(0, str.indexOf("}")+1); }
通過上面的兩個函數,我們可以將字符串轉化成Json字符串,並能通過關鍵字來提取對應數據。
如果要提取的數據是第一層里面的,可以直接提取,如:GetJsonValue (jresult,0,”error”);
如果要提出的數據在data中或是更深的json中,則需要指示是第幾個數據了,數據以1開始計數,
如:GetJsonValue(jresult,2,”name”) 表示獲取第二個數據項的name字段的值。
借助於這兩個函數,我們可以根據Key來提取出需要的數據,進而去做我們測試用例的判斷,完成對接口的自動化測試。當然我們還可以根據自己業務的需要,去封裝獲取你需要的數據的函數,以減少工作量。
經過上面我們封裝的調用函數,結果處理函數,就可以通過java代碼來完成對HTTP請求的API的調用,數據的獲取等功能,下面我們實踐一下:
public static void main( String[] args ) { // Get接口調用 String url="http://api.zhongchou.cn/deal/list"; String params="?v=1"; String apiresult=GetRequests(url,params); System.out.println("errno:"+GetJsonValue(apiresult,0,"errno"));//獲取接口返回代碼 System.out.println("name:"+GetJsonValue(apiresult,3,"name"));//獲取第三個項目的項目名稱 //Post接口調用 String posturl="http://api.zhongchou.cn/user/login?v=1"; Map map = new IdentityHashMap (); map.put("identity", "183****8905"); map.put("password", "**********"); String poresult=PostRequests(posturl,map,null); //獲取登錄的用戶帳號昵稱 System.out.println("Name:"+GetJsonValue(poresult,1,"name")); }