2011-05-09
android网络编程
编程AndroidjsonQQStruts转自:http://www.linuxidc.com/Linux/2011-04/35009.htm
(http://www.blogjava.net/changcheng/archive/2010/03/04/314496.html)
Android 网络编程---STRUTS2,JSON,HttpClient
在Android开发过程中,我们需要访问网络上的Web资源,比如网络上的WEB请求。在这里Android就好像是一个终端,可以用来接收Web服务器端发送过来的数据。下面我以Struts2作为Web服务器端的Web框架。来说明Android客户端接收Web请求的过程。
首先,我们要配置Web服务器端,添加Struts2所需要的JAR包(包括JSON包)
下面是服务器端所要配置的JAR包,如下所示:
我们看看json包,有如下: json-lib-**.jdk15.jar,struts2-json-plugin-***.jar,ezmorph-**.jar
接下配置web.xml文件,代码如下所示:
1.
2.
3.
4. struts2
5.
6. org.apache.struts2.dispatcher.FilterDispatcher
7. 8.
9.
10. struts2
11. /*
12. 添加完JAR包后。我们来配置一下struts.xml文件,这个文件存放在src根目录下面,代码如下所示:
1.
2. 3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4. "http://struts.apache.org/dtds/struts-2.0.dtd">
5.
6.
9.
10. 11. value="true">
12.
13.
17.
18.
19.
20. 21. method="login">
22.
23.
24.
25.
26. 看看这个action
method="login">
返回的是json 数据。而且是由LoginAction类去处理,它存放在com.dongzi.action下面。LoginAction类的代码如下:
1. public class LoginAction extends ActionSupport implements ServletRequestAware,
2. ServletResponseAware {
3. /**
4. *
5. */
6. private static final long serialVersionUID = 1L;
7. HttpServletRequest request;
8. HttpServletResponse response;
9. public void setServletRequest(HttpServletRequest request) {
10. this.request = request;
11. }
12. public void setServletResponse(HttpServletResponse response) {
13. this.response = response;
14. }
15. public void login() {
16. try {
17. // HttpServletRequest request =ServletActionContext.getRequest();
18. // HttpServletResponse response=ServletActionContext.getResponse();
19. this.response.setContentType("text/html;charset=utf-8");
20. this.response.setCharacterEncoding("UTF-8");
21. // 将要返回的实体对象进行json处理
22. // JSONObject json=JSONObject.fromObject(this.getUsername());
23. // 输出格式如:{"id":1, "username":"zhangsan", "pwd":"123"}
24. // System.out.println(json);
25.
26. // this.response.getWriter().write(json.toString());
27.
28. //{"username":"mingg","password":"123"}
29. JSONObject json=new JSONObject();
30. // json.put("username", "mingg");
31. // json.put("password","123");
32.
33.
34.
35. //【这里在JSON中包含一个Map】
36. Map map=new HashMap