日期:2014-05-16  浏览次数:20318 次

Android 下使用 JSON 实现 HTTP 请求

最近在用Android调用Web服务,开始准备用WebService来调用,用jws的WebService方式写好后发现Android调用的时候很多问题不知道咋解决了,后来发现有一个更好的办法,就是采用HttpPost来与后台交互。

下面就说一下相关的JSON的操作:

?

不得不说,JSON 格式的确是非常美妙的,速度快而且简化了很多操作
在 Android 下,Android SDK 已经为我们封装好了整个与 JSON 有关的操作,使用非常方便

以下就是一个标准的 JSON 请求的实现过程:

HttpPost request = new HttpPost(url);
// 先封装一个 JSON 对象
JSONObject param = new JSONObject();
param.put("name", "rarnu");
param.put("password", "123456");
// 绑定到请求 Entry
StringEntity se = new StringEntity(param.toString());
request.setEntity(se);
// 发送请求
HttpResponse httpResponse = new DefaultHttpClient().execute(request);
// 得到应答的字符串,这也是一个 JSON 格式保存的数据
String retSrc = EntityUtils.toString(httpResponse.getEntity());
// 生成 JSON 对象
JSONObject result = new JSONObject( retSrc);
String token = result.get("token");

1 楼 cnflood 2011-07-22  
谢谢分享,但是这样的数据传到后服务端后,服务端怎么解析呢

2 楼 liangjian103 2011-07-24  
cnflood 写道
谢谢分享,但是这样的数据传到后服务端后,服务端怎么解析呢


就正常解析JSON就可以了。
例如:

/**查询新闻列表 */
public void queryByNewsList()throws Exception{
List<Map<Object,Object>> newsList = newsService.QueryByTop_Android(10);//查询新闻列表前10条
//System.out.println("已经到服务器了!"+newsList);
net.sf.json.JSONArray jsonAry = new net.sf.json.JSONArray();
for(Map<Object,Object> m:newsList){
String news_date = new SimpleDateFormat("yyyy-MM-dd").format((Date)m.get("news_date")); 
net.sf.json.JSONObject json = new net.sf.json.JSONObject();
json.put("news_id", m.get("news_id")+"");
json.put("news_title", m.get("news_title")+"");
json.put("news_date", news_date+"");
json.put("sort_id", m.get("sort_id")+"");
json.put("sort_name", m.get("sort_name")+"");
jsonAry.add(json);
}

//System.out.println("服务端组装JSON数据:");
//System.out.println(jsonAry);

byte[] jsonBytes = jsonAry.toString().getBytes("utf-8");
response.setContentType("text/html;charset=utf-8");
response.setContentLength(jsonBytes.length);
response.getOutputStream().write(jsonBytes);
response.getOutputStream().flush();
response.getOutputStream().close();   
}

/**查询新闻列表-查询指定条数区间 */
public void queryByNewsLimit()throws Exception{
//System.out.println("查询"+num01+"条开始,的后"+num02+"条新闻");
List<Map<Object,Object>> newsList = newsService.QueryByLimit(num01, num02);//查询新闻列表前10条
//System.out.println("已经到服务器了!"+newsList);
net.sf.json.JSONArray jsonAry = new net.sf.json.JSONArray();
for(Map<Object,Object> m:newsList){
String news_date = new SimpleDateFormat("yyyy-MM-dd").format((Date)m.get("news_date")); 
net.sf.json.JSONObject json = new net.sf.json.JSONObject();
json.put("news_id", m.get("news_id")+"");
json.put("news_title", m.get("news_title")+"");
json.put("news_date", news_date+"");
json.put("sort_id", m.get("sort_id")+"");
json.put("sort_name", m.get("sort_name")+"");