现在的位置: 首页 > 综合 > 正文

Android 下使用 JSON 实现 HTTP 请求(自整合而来)

2013年10月07日 ⁄ 综合 ⁄ 共 1615字 ⁄ 字号 评论关闭

最近在用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");

发送Json请求,结果返回Json.

Java代码  收藏代码
  1. public static JSONObject post(String url,JSONObject json){  
  2.         HttpClient client = new DefaultHttpClient();  
  3.         HttpPost post = new HttpPost(url);  
  4.         JSONObject response = null;  
  5.         try {  
  6.             StringEntity s = new StringEntity(json.toString());  
  7.             s.setContentEncoding("UTF-8");  
  8.             s.setContentType("application/json");  
  9.             post.setEntity(s);  
  10.               
  11.             HttpResponse res = client.execute(post);  
  12.             if(res.getStatusLine().getStatusCode() == HttpStatus.OK.value()){  
  13.                 HttpEntity entity = res.getEntity();  
  14.                 String charset = EntityUtils.getContentCharSet(entity);  
  15.                 response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(),charset)));  
  16.             }  
  17.         } catch (Exception e) {  
  18.             throw new RuntimeException(e);  
  19.         }  
  20.       

抱歉!评论已关闭.