android 客户端和服务器端交互

mc54 贡献于2013-11-23

作者 Sky123.Org  创建于2012-10-22 15:02:00   修改者Sky123.Org  修改于2012-10-22 15:03:00字数2049

文档摘要:android 客户端和服务器端交互
关键词:

Public class Action extends ActionSupport implements ServletRequestAware,ServletResponseAware{ private String Json; private int age; private String name; private String password; private HttpServletRequest request; private HttpServletResponse response; public void execute() { try{ JSONObject obj=new JSONObject(this.getJson()) this.setAge(obj.getInt("age")); this.setName(obj.getString("name")); this.setPassword(obj.getString("password")); }catch(org.json.JSONException e) { e.printStack(); } JSONObject object=new JSONObject(); object.put("age",22); object.put("name",nikerlover); object.put("password",12345); JSONObject tem=new JSONObject();//若需要传递数组,夹杂其他的杂项,可以用Map map=new HashMap()将数据封装好,创建List> list=new ArrayList>(),然后,list.add(map);再用JSONObject进行封装,JSONObject和JSONArray可以相互嵌套,你懂的 JSONObject temp=new JSONObject(); try{ tem.put("user",object); temp.put("json",tem); response.setCharacterEncoding("UTF-8"); response.getWriter().write(temp.toString()); }catch(Exception e) { e.printStackTrace(); } } // Getter and Setter method //public void setServletResponse(HttpServletResponse) . . } Android客户端:先给服务器发送一个封装好了的JSON对象,再等待服务器反送response对象,将response里的JSON对象获取并解析 pubic void OnCreate(Handler instance) { String Url="http://59.64.34.45/project/index.action"; HttpClient client=new DefaultHttpClient(); HttpPost post=new HttpPost(url); List pair=new ArrayList()' try{ JSONObject obj=new JSONObject(); obj.put("age",2); obj.put("name",nikerlover); obj.put("password",45667); JSONObject json=new JSONObject(); pair.add(new BasicValueNamePair("json",obj.toString())); post.setEntity(new UrlEncodedFormEntity(pair,HTTP.UTF_8)); HttpResponse response=client.execute(post); if(response.getStatusLine().getStatusCode()==200) { String responseStr=EntityUtils.toString(response.getEntity()); JSONObject json=new JSONObject(responseStr).getJSONObject("json"); JSONObject object=json.getJSONObject("user"); int Age=obj.getInt("age"); String Name=obj.getString("name"); String Password=obj.getString("password"); } } } 本篇文章来源于 Linux公社网站(www.linuxidc.com) 原文链接:http://www.linuxidc.com/Linux/2011-10/45151.htm

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 2 金币 [ 分享文档获得金币 ] 0 人已下载

下载文档