標籤:hashmap put http請求 判斷 計數 indexof 需要 實踐 com
介面傳回值結果轉換成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")); }
介面傳回值結果轉換成JSON