在使用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();