FastJson - 從HttpEntity到Json

在使用java + httpClient施行API自動化時,不可避免地遇到了以下問題:java

1. 用Http Response數據作斷言;json

2. 用上一個請求的Response內容,做爲下一個請求的參數;post

若是用jmeter來作的話,首選固然是BeanShell。然而,當須要本身寫的時候(經過java + httpClient),在此我用到了FastJson。url

1. 以一個Post請求爲例,代碼以下:spa

 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):code

1 int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();

  3. 提取返回實體(httpEntity):對象

1 HttpEntity entity = closeableHttpResponse.getEntity();
2 System.out.println(entity);

此時的輸出結果爲:blog

4. HttpEntity 轉化爲 String:字符串

1 String responseEntity = EntityUtils.toString(entity);
2 System.out.println(responseEntity);

此時的輸出結果爲String格式,提取code、message等值,只能經過字符串截取:get

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();
相關文章
相關標籤/搜索