FastJson - 从HttpEntity到Json

在使用java + httpClient施行API自动化时,不可避免地遇到了如下问题:

1. 用Http Response数据做断言;

2. 用上一个请求的Response内容,作为下一个请求的参数;

如果用jmeter来做的话,首选当然是BeanShell。然而,当需要自己写的时候(通过java + httpClient),在此我用到了FastJson。

1. 以一个Post请求为例,代码如下:

     public CloseableHttpResponse post(String url , String entityString , HashMap<String , String> headermap)
throws ClientProtocolException, IOException {
//创建一个可关闭的 httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建一个HttpPost的请求对象
HttpPost httpPost = new HttpPost(url);
//设置payload
httpPost.setEntity(new StringEntity(entityString));
//加载请求头到HttpPost对象
for (Map.Entry<String , String> entry : headermap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
//发送post请求
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
return httpResponse;
}

2. 发送Post请求后,我们会得到一个CloseableHttpResponse。接下来,我们提取状态码(status):

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

  3. 提取返回实体(httpEntity):

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

此时的输出结果为:

FastJson - 从HttpEntity到Json

4. HttpEntity 转化为 String:

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

此时的输出结果为String格式,提取code、message等值,只能通过字符串截取:

FastJson - 从HttpEntity到Json

5. String 转化为 JsonObject:

 JSONObject jsonObject = JSON.parseObject(responseEntity);
System.out.println(jsonObject);

此时的输出结果为JsonObject格式:

FastJson - 从HttpEntity到Json

6. 提取code、message的值:

 String responseCode = jsonObject.getString("code");
String responseMessage = jsonObject.getString("message");

7. 提取orderId:

 //由于info的值是json格式(或可理解为key-value集合),提取info的值为JSONObject格式
JSONObject infoObject = jsonObject.getJSONObject("info");
//重复步骤6,提取orderId
String orderId= jsonObject.getString("orderId");
//或通过将infoObject转化为HashMap,再进行提取orderId
HashMap<String, Object> info = new HashMap<String, Object>();
info = JSON.parseObject(String.valueOf(infoObject), new TypeReference<HashMap<String, Object>>() {});
String orderId = info.get("orderId").toString();
上一篇:HDU 2035 人见人爱A^B 分类: ACM 2015-06-22 23:54 9人阅读 评论(0) 收藏


下一篇:洛谷P4211 LCA