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