1 import com.alibaba.fastjson.JSON;
2 import com.alibaba.fastjson.JSONObject;
3 import com.qa.base.TestBase;
4 import com.qa.util.RestClient;
5 import com.qa.util.JsonUtil;
6 import org.apache.http.client.methods.CloseableHttpResponse;
7 import org.apache.http.util.EntityUtils;
8 import org.testng.Assert;
9 import org.testng.annotations.BeforeClass;
10 import org.testng.annotations.Test;
11 import java.io.IOException;
12 import java.util.*;
13
14
15 public class GetDemo extends TestBase {
16 TestBase testBase;
17 String host;
18 String url;
19 RestClient restClient;
20 CloseableHttpResponse closeableHttpResponse;
21
22 @BeforeClass
23 public void setup() {
24 testBase = new TestBase();
25 host = prop.getProperty("GETPOST");
26 url = host + "api/users";
27 }
28
29 //get方法带请求头
30 @Test(description = "get请求成功")
31 public void getAPITest() throws IOException {
32 restClient = new RestClient();
33 restClient.get(url);
34 HashMap<String, String> hashMap = new HashMap<String, String>();
35 hashMap.put("Content-Type", "application/json");
36 closeableHttpResponse = restClient.get(url, hashMap);
37 //断言状态码
38 int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
39 System.out.println(statusCode);
40 Assert.assertEquals(statusCode, RESPNSE_STATUS_CODE_200, "状态码不是200");
41 //把响应内容存储在字符串对象
42 String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
43 //System.out.println(responseString);
44 JSONObject responseJson = JSON.parseObject(responseString);
45 //json内容解析
46 String s = JsonUtil.getValueByJPath(responseJson, "data[0]/first_name");
47 //断言第一个名字是否是"George"
48 Assert.assertEquals(s, "George", "fiset_name is not George");
49 }
50
51 }
//把响应内容存储在字符串对象
//得到相应报文的字符集
String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
1 CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
2 if(httpResponse.getStatusLine().getStatusCode() == 200) {
3 //网站转为String
4 String get_Charset_Entity2String = EntityUtils.toString(httpResponse.getEntity());
5 //解析
6 Document get_Charset_Document = Jsoup.parse(get_Charset_Entity2String);
7 //字符集信息提取,51job和猎聘
8 String charset = get_Charset_Document.select("meta[http-equiv=Content-Type]")
9 .attr("content").split("=")[1];
10 System.out.println(charset);
11 //根据字符集重新编码成正确的
12 String Ori_Entity = EntityUtils.toString(httpResponse.getEntity(),charset);
13 //转换为统一的utf-8
14 String entity = new String(Ori_Entity.getBytes(),"utf-8");
15 System.out.println(entity); {
//字符串对象转换成json对象,以便取值
JSONObject responseJson = JSON.parseObject(responseString);
1 //举例 result为
2 {
3
4 "success":"true",
5
6 "returnAddress":"123"
7
8 }
9 JSONObject jsonObject=JSON.parseObject(result); //转换成object
10
11 jsonObject.getString("returnAddress") //获取object中returnAddress字段值123;