在使用java + httpClient施行API自動化時,不可避免地遇到了如下問題:
1. 用Http Response數據做斷言;
2. 用上一個請求的Response內容,作為下一個請求的參數;
如果用jmeter來做的話,首選當然是BeanShell。然而,當需要自己寫的時候(通過java + httpClient),在此我用到了FastJson。
1. 以一個Post請求為例,代碼如下:
1 public CloseableHttpResponse post(String url , String entityString , HashMap<String , String> headermap) 2 throws ClientProtocolException, IOException { 3 //創建一個可關閉的 httpClient對象 4 CloseableHttpClient httpClient = HttpClients.createDefault(); 5 //創建一個HttpPost的請求對象 6 HttpPost httpPost = new HttpPost(url); 7 //設置payload 8 httpPost.setEntity(new StringEntity(entityString)); 9 //加載請求頭到HttpPost對象 10 for (Map.Entry<String , String> entry : headermap.entrySet()) { 11 httpPost.addHeader(entry.getKey(), entry.getValue()); 12 } 13 //發送post請求 14 CloseableHttpResponse httpResponse = httpClient.execute(httpPost); 15 return httpResponse; 16 }
2. 發送Post請求后,我們會得到一個CloseableHttpResponse。接下來,我們提取狀態碼(status):
1 int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
3. 提取返回實體(httpEntity):
1 HttpEntity entity = closeableHttpResponse.getEntity(); 2 System.out.println(entity);
此時的輸出結果為:
4. HttpEntity 轉化為 String:
1 String responseEntity = EntityUtils.toString(entity); 2 System.out.println(responseEntity);
此時的輸出結果為String格式,提取code、message等值,只能通過字符串截取:
5. String 轉化為 JsonObject:
1 JSONObject jsonObject = JSON.parseObject(responseEntity); 2 System.out.println(jsonObject);
此時的輸出結果為JsonObject格式:
6. 提取code、message的值:
1 String responseCode = jsonObject.getString("code"); 2 String responseMessage = jsonObject.getString("message");
7. 提取orderId:
1 //由於info的值是json格式(或可理解為key-value集合),提取info的值為JSONObject格式 2 JSONObject infoObject = jsonObject.getJSONObject("info"); 3 //重復步驟6,提取orderId 4 String orderId= jsonObject.getString("orderId"); 5 //或通過將infoObject轉化為HashMap,再進行提取orderId 6 HashMap<String, Object> info = new HashMap<String, Object>(); 7 info = JSON.parseObject(String.valueOf(infoObject), new TypeReference<HashMap<String, Object>>() {}); 8 String orderId = info.get("orderId").toString();