首页 > Web开发 > 详细

一.HttpClient、JsonPath、JsonObject运用

时间:2016-11-24 08:27:57      阅读:225      评论:0      收藏:0      [点我收藏+]

HttpClient详细应用请参考官方api文档:http://hc.apache.org/httpcomponents-client-4.5.x/httpclient/apidocs/index.html

1.使用httpclient进行接口测试,所需jar包如下:httpclient.jar、 httpcore.jar、 commons-logging.jar


 2.使用JSONObject插件处理响应数据
 所需的6个JAR包:json-lib.jar、commons-beanutils.jar、commons-collections.jar、ezmorph.jar、commons-logging.jar、commons-lang.jar

3.使用正则表达式匹配提取响应数据

 

  1 public class UserApiTest {
  2     private static CloseableHttpClient httpClient = null;
  3     
  4     @BeforeClass
  5     public static void setUp(){
  6         httpClient = HttpClients.createDefault();    //创建httpClient
  7     }
  8     
  9     @AfterClass
 10     public static void terDown() throws IOException{
 11         httpClient.close();    
 12     }
 13     
 14     /*    
 15      * 使用httpclient进行接口测试,所需jar包如下:
 16      *httpclient.jar、 httpcore.jar、 commons-logging.jar
 17      *get请求
 18      **/
 19     @Test
 20     public void userQueryWithRegTest1() throws ClientProtocolException, IOException{
 21         HttpGet request = new HttpGet("url地址");    // 创建请求
 22         //设置请求和连接超时时间,可以不设置
 23         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(20000).build();
 24         request.setConfig(requestConfig);    //get请求设置请求和传输超时时间
 25         CloseableHttpResponse response = httpClient.execute(request);    //执行请求
 26         String body = EntityUtils.toString(response.getEntity());
 27         response.close();          //释放连接
 28         System.out.println(body);
 29         
 30         //获取响应头信息
 31         Header headers[] = response.getAllHeaders();
 32         for(Header header:headers){
 33             System.out.println(header.getName()+""+header.getValue());
 34         }
 35         
 36         // 打印响应信息
 37         System.out.println(response.getStatusLine().getStatusCode());
 38     }
 39     
 40     /*    
 41      * 使用httpclient进行接口测试,所需jar包如下:
 42      *httpclient.jar、 httpcore.jar、 commons-logging.jar
 43      *get请求
 44      **/
 45     @Test
 46     public void testPost1() throws ClientProtocolException, IOException{
 47         HttpPost request = new HttpPost("http://101.200.167.51:8080/fund-api/expProduct");
 48         //设置post请求参数
 49         List<NameValuePair> foramParams = new ArrayList<NameValuePair>();
 50         foramParams.add(new BasicNameValuePair("name", "新手体验"));
 51         foramParams.add(new BasicNameValuePair("yieldRate", "7"));
 52         foramParams.add(new BasicNameValuePair("extraYieldRate", "2"));
 53         foramParams.add(new BasicNameValuePair("duration", "3"));
 54         foramParams.add(new BasicNameValuePair("minBidAmount", "0"));
 55         foramParams.add(new BasicNameValuePair("maxBidAmount", "10000"));
 56         UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(foramParams, "UTF-8");
 57         request.setEntity(urlEntity);  //设置POST请求参数
 58         CloseableHttpResponse response = httpClient.execute(request);    //执行post请求
 59         String body = EntityUtils.toString(response.getEntity());    
 60         response.close();    //释放连接
 61         System.out.println(body);
 62         JSONObject jsonObj = JSONObject.fromObject(body);
 63         System.out.println("是否成功:"+jsonObj.getString("msg").equals("成功"));
 64     }
 65 
 66     /*
 67      * 用正则表达式提取响应数据
 68      * */
 69     @Test
 70     public void userQueryWithRegTest2() throws ClientProtocolException, IOException{
 71         HttpGet request = new HttpGet("url地址"); // 创建请求
 72         CloseableHttpResponse response = httpClient.execute(request);    // 执行某个请求
 73         String body = EntityUtils.toString(response.getEntity());    // 得到响应内容
 74         response.close();
 75         System.out.println(body);
 76 
 77         // "nickname":"([a-zA-Z0-9]*)"
 78         Pattern pattern = Pattern.compile("\"mobile\":\"(\\d+)\",\"nickname\":\"([a-zA-Z0-9]*)\".*\"status\":(\\d)"); // 从正则表达式得到一个模式对象
 79         Matcher matcher = pattern.matcher(body);// 对响应内容进行匹配
 80         while (matcher.find()) {
 81             String group0 = matcher.group(0); // **_g0
 82             String group1 = matcher.group(1); // **_g1
 83             String group2 = matcher.group(2); // **_g1
 84             String group3 = matcher.group(3); // **_g1
 85             System.out.println(group0 + "\t" + group1 + "\t" + group2 + "\t" + group3);
 86         }
 87 
 88     }
 89     
 90     /*
 91      * 使用JsonPath提取json响应数据中的数据
 92      * 需要的jar包:json-path-2.2.0.jar
 93      */
 94     @Test
 95     public void userQueryWithRegTest3() throws ClientProtocolException, IOException{
 96         HttpGet request = new HttpGet("url地址"); // 创建请求
 97         CloseableHttpResponse response = httpClient.execute(request);    // 执行某个请求
 98         String body = EntityUtils.toString(response.getEntity());    // 得到响应内容
 99         response.close();
100         System.out.println(body);
101 
102         ReadContext ctx = JsonPath.parse(body);
103         String  mobile = ctx.read("$.data.mobile");
104         String  nickname = ctx.read("$.data.nickname");
105         int status = ctx.read("$.data.status");
106         String avatar = ctx.read("$.data.avatar");
107         System.out.println(mobile + "\t" + nickname + "\t" + status + "\t" + avatar);
108     }
109     
110         
111     
112         /*
113          * 使用JSONObject插件处理响应数据
114          * 所需的6个JAR包:json-lib.jar、commons-beanutils.jar、commons-collections.jar、ezmorph.jar、commons-logging.jar、commons-lang.jar
115          */
116     @Test
117     public void userQueryWithRegTest5() throws ClientProtocolException, IOException{
118         HttpGet request = new HttpGet("url地址"); // 创建请求
119         CloseableHttpResponse response = httpClient.execute(request);    // 执行某个请求
120         String body = EntityUtils.toString(response.getEntity());    // 得到响应内容
121         response.close();
122         
123         //将响应的字符串转换为JSONObject对象
124         JSONObject jsonObj = JSONObject.fromObject(body);
125         System.out.println(jsonObj.getString("code").equals("200"));
126         //data是对象中的一个对象,使用getJSONObject()获取
127         JSONObject jsonObj1 = jsonObj.getJSONObject("data");
128         System.out.println("status:"+jsonObj1.getInt("status")+"\n"+"nickname:"+jsonObj1.getString("nickname"));
129     }
130     
131     
132     
133     /*
134      * java代码转换json
135      * 需要的jar包:json-lib
136      * */
137     @Test
138     public void testJavaToJson(){
139         System.out.println("--------------------------------------------------------------");
140         System.out.println("java代码封装为json字符串:");
141         JSONObject jsonObj = new JSONObject();
142         jsonObj.put("username", "张三");
143         jsonObj.put("password", "123456");
144         System.out.println("java--->json: "+jsonObj.toString());
145         System.out.println("--------------------------------------------------------------");
146     }
147     
148     /*
149      * json字符串转xml字符串
150      * 需要的jar包:json-lib;xom
151      * */
152     @Test
153     public void testJsonToXml(){
154         System.out.println("--------------------------------------------------------------");
155         System.out.println("json转xml字符串");
156         String jsonStr = "{\"username\":\"张三\",\"password\":\"123456\"}";
157         JSONObject jsonObj = JSONObject.fromObject(jsonStr);
158         XMLSerializer xmlSerializer = new XMLSerializer();
159         // 设置根元素名称
160         xmlSerializer.setRootName("user_info");
161         // 设置类型提示,即是否为元素添加类型 type = "string"
162         xmlSerializer.setTypeHintsEnabled(false);
163         String xml = xmlSerializer.write(jsonObj);
164         System.out.println("json--->xml: "+xml);
165         System.out.println("--------------------------------------------------------------");
166     }
167     
168     /*
169      * xml字符串转json字符串
170      * 需要的jar包:json-lib;xom
171      * */
172     @Test
173     public void testXmlToJson(){
174         System.out.println("--------------------------------------------------------------");
175         System.out.println("xml字符串转json字符串");
176         String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user_info><password>123456</password><username>张三</username></user_info>";
177         XMLSerializer xmlSerializer = new XMLSerializer();
178         JSON json= xmlSerializer.read(xml);    //JSON是JSONObject的String形式
179         System.out.println("xml---->json:"+json);
180         System.out.println("--------------------------------------------------------------");
181     }
182     
183     /*
184      * javaBean转json
185      * 需要的jar包:json-lib
186      * */
187     @Test
188     public void testJavaBeanToJson(){
189         System.out.println("--------------------------------------------------------------");
190         System.out.println("javaBean转json");
191         UserInfo userInfo = new UserInfo();
192         userInfo.setUsername("张三");
193         userInfo.setPassword("123456");
194         JSONObject JsonObj = JSONObject.fromObject(userInfo);
195         System.out.println("javaBean--->json:"+JsonObj.toString());
196         System.out.println("--------------------------------------------------------------");
197     }
198     
199     /*
200      * javaBean转xml
201      * 需要的jar包:json-lib;xom
202      * */
203     @Test
204     public void testJavaBeanToXml(){
205         System.out.println("--------------------------------------------------------------");
206         System.out.println("javaBean转xml");
207         UserInfo userInfo = new UserInfo();
208         userInfo.setUsername("张三");
209         userInfo.setPassword("123456");
210         JSONObject JsonObj = JSONObject.fromObject(userInfo);
211         XMLSerializer xmlSerializer = new XMLSerializer();
212         xmlSerializer.setRootName("user_info");
213         String xml = xmlSerializer.write(JsonObj, "UTF-8");
214         System.out.println("javaBeanToXml--->xml:"+xml);
215         System.out.println("--------------------------------------------------------------");
216     }
217 }

UserInfo:

public class UserInfo {
    public String username;
    public String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
}

 

一.HttpClient、JsonPath、JsonObject运用

原文:http://www.cnblogs.com/gongjian/p/6095669.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!