使用httpClient进行接口测试

概述

现今很多Web应用开发都是分前后台的,后台开发提供接口调用返回Json对象,前台使用JS框架去加载后台返回的Json.本文以实例简述如何通过HttpClient测试这样的后台接口

 处理Json对象的基本API

JSON包中最常用的两个类就是JSONObject和JSONArray,具体可以参考JSON for java入门总结

如下是自己模仿的简单例子:

Java代码 复制代码  收藏代码
  1. package com.james.json;   
  2.   
  3. import org.json.JSONArray;   
  4. import org.json.JSONObject;   
  5.   
  6. public class JsonTest {   
  7.   
  8.     public static void main(String[] args) {   
  9.            
  10.         // Test JSONObject.   
  11.         JSONObject jsonobj = new JSONObject("{'name':'jingshou','age':30}");     
  12.         String name = jsonobj.getString("name");     
  13.         int age = jsonobj.getInt("age");   
  14.         System.out.println(jsonobj.toString());   
  15.         System.out.println(name+":"+age);    
  16.         System.out.println("**********");   
  17.            
  18.         // Test JSONArray.   
  19.         JSONArray jsonarray = new JSONArray("[{'name':'jingshou','age':30},{'name':'xiaohong','age':29}]");     
  20.         for(int i=0;i<jsonarray.length();i++){   
  21.             JSONObject jo = jsonarray.getJSONObject(i);   
  22.             System.out.println(jo);   
  23.             String name1 = jo.getString("name");   
  24.             int age1 = jo.getInt("age");   
  25.             System.out.println("name1= "+name1);   
  26.             System.out.println("age1= "+age1);   
  27.         }   
  28.     }   
  29.        
  30.   
  31. }  
package com.james.json;

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonTest {

	public static void main(String[] args) {
		
		// Test JSONObject.
		JSONObject jsonobj = new JSONObject("{'name':'jingshou','age':30}");  
        String name = jsonobj.getString("name");  
        int age = jsonobj.getInt("age");
        System.out.println(jsonobj.toString());
        System.out.println(name+":"+age); 
        System.out.println("**********");
        
        // Test JSONArray.
        JSONArray jsonarray = new JSONArray("[{'name':'jingshou','age':30},{'name':'xiaohong','age':29}]");  
        for(int i=0;i<jsonarray.length();i++){
        	JSONObject jo = jsonarray.getJSONObject(i);
        	System.out.println(jo);
            String name1 = jo.getString("name");
            int age1 = jo.getInt("age");
            System.out.println("name1= "+name1);
            System.out.println("age1= "+age1);
        }
	}
	

}

 运行结果如下:

Java代码 复制代码  收藏代码
  1. {"age":30,"name":"jingshou"}   
  2. jingshou:30  
  3. **********   
  4. {"age":30,"name":"jingshou"}   
  5. name1= jingshou   
  6. age1= 30  
  7. {"age":29,"name":"xiaohong"}   
  8. name1= xiaohong   
  9. age1= 29  
{"age":30,"name":"jingshou"}
jingshou:30
**********
{"age":30,"name":"jingshou"}
name1= jingshou
age1= 30
{"age":29,"name":"xiaohong"}
name1= xiaohong
age1= 29

 从以上例子我们看到的基本事实是:

  • 可以通过字符串直接构造一个JSONObject
  • JSONObject里的key在显式传入的时候是用单引号包裹起来的,但是打印出来的时候依然是我们期望的双引号

使用httpclient处理API返回

如下例子演示如何使用httpClient获取API返回的JSON字符串以及处理:

Java代码 复制代码  收藏代码
  1. package com.james.json;   
  2.   
  3. import java.io.IOException;   
  4.   
  5. import org.apache.http.HttpEntity;   
  6. import org.apache.http.client.ClientProtocolException;   
  7. import org.apache.http.client.methods.CloseableHttpResponse;   
  8. import org.apache.http.client.methods.HttpPost;   
  9. import org.apache.http.impl.client.CloseableHttpClient;   
  10. import org.apache.http.impl.client.HttpClients;   
  11. import org.apache.http.util.EntityUtils;   
  12. import org.json.JSONArray;   
  13. import org.json.JSONObject;   
  14.   
  15.   
  16. public class SimpleServiceTest {   
  17.   
  18.     public static void main(String[] args) throws ClientProtocolException, IOException {   
  19.         CloseableHttpClient httpclient = HttpClients.createDefault();   
  20.         HttpPost httppost = new HttpPost("http://jingshou.com/admin/searchUser.action?search_loginid=jingshou");   
  21.         CloseableHttpResponse response = httpclient.execute(httppost);   
  22.         try {   
  23.             HttpEntity myEntity = response.getEntity();   
  24.             System.out.println(myEntity.getContentType());   
  25.             System.out.println(myEntity.getContentLength());   
  26.                
  27.             String resString = EntityUtils.toString(myEntity);   
  28.             // 使用返回的字符串直接构造一个JSONObject       
  29.             JSONObject jsonobj = new JSONObject(resString);   
  30.             System.out.println(jsonobj.toString());   
  31.             // 获取返回对象中"resultSize的值"   
  32.             int resutltSize = jsonobj.getInt("resultSize");   
  33.             System.out.println("Search Results Size is: "+ resutltSize);    
  34.             // 获取"clients"的值,它是一个JSONArray  
  35.             JSONArray jsonarray = jsonobj.getJSONArray("clients");   
  36.             System.out.println(jsonarray.toString());   
  37.                
  38.                
  39.         } finally {   
  40.             response.close();   
  41.         }   
  42.            
  43.            
  44.     }   
  45.   
  46. }  
package com.james.json;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;


public class SimpleServiceTest {

	public static void main(String[] args) throws ClientProtocolException, IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost("http://jingshou.com/admin/searchUser.action?search_loginid=jingshou");
		CloseableHttpResponse response = httpclient.execute(httppost);
		try {
			HttpEntity myEntity = response.getEntity();
			System.out.println(myEntity.getContentType());
			System.out.println(myEntity.getContentLength());
			
			String resString = EntityUtils.toString(myEntity);
            // 使用返回的字符串直接构造一个JSONObject		
			JSONObject jsonobj = new JSONObject(resString);
			System.out.println(jsonobj.toString());
			// 获取返回对象中"resultSize的值"
			int resutltSize = jsonobj.getInt("resultSize");
			System.out.println("Search Results Size is: "+ resutltSize); 
			// 获取"clients"的值,它是一个JSONArray
			JSONArray jsonarray = jsonobj.getJSONArray("clients");
			System.out.println(jsonarray.toString());
			
	        
		} finally {
		    response.close();
		}
		
		
	}

}

运行结果如下:

Java代码 复制代码  收藏代码
  1. Content-Type: text/plain; charset=UTF-8  
  2. -1  
  3. {"resultSize":1,"clients":[{"expirationDate":0,"reqStatus":0,"mostRecentActivity":1388376890000,"clientName":"Jingshou Li","company":"Pending","internal":true,"clientId":"jingshou","salesNames":"","disabled":false}]}   
  4. Search Results Size is: 1  
  5. [{"expirationDate":0,"reqStatus":0,"mostRecentActivity":1388376890000,"clientName":"Jingshou Li","company":"Pending","internal":true,"clientId":"jingshou","salesNames":"","disabled":false}]  
Content-Type: text/plain; charset=UTF-8
-1
{"resultSize":1,"clients":[{"expirationDate":0,"reqStatus":0,"mostRecentActivity":1388376890000,"clientName":"Jingshou Li","company":"Pending","internal":true,"clientId":"jingshou","salesNames":"","disabled":false}]}
Search Results Size is: 1
[{"expirationDate":0,"reqStatus":0,"mostRecentActivity":1388376890000,"clientName":"Jingshou Li","company":"Pending","internal":true,"clientId":"jingshou","salesNames":"","disabled":false}]

 小结:

  • 通过API返回的JSON字符串直接构造JSON对象
  • 如果要读取JSONObject内部数据,需要事先知道对象的结构,所以以上处理方法不具有通用性,只能处理特定的返回

补充学习:

  • http://cgs1999.iteye.com/blog/1608003
  • http://cgs1999.iteye.com/blog/1609756
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值