ITeye博客

android网络编程

xihuan&java · 2011-05-09 09:57 · android · 移动开发 · Markdown

转自: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.  <!-- 定义核心Filter的名称 -->  
    
  2.  <filter-name>struts2</filter-name>  
    
  3.  <!-- 定义Filter的实现类 -->  
    
  4.  <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  
    
  5.  <filter-name>struts2</filter-name>  
    
  6.  <url-pattern>/*</url-pattern>  
    

添加完JAR包后。我们来配置一下struts.xml文件,这个文件存放在src根目录下面,代码如下所示:

  1. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  2. "http://struts.apache.org/dtds/struts-2.0.dtd">
  3. <!-- setting encoding,DynamicMethod,language   
    
  4.     <constant name="struts.custom.i18n.resources" value="messageResource"></constant>  
    
  5. -->  
    
  6. <constant name="struts.i18n.encoding" value="UTF-8"></constant>  
    
  7. <constant name="struts.enable.DynamicMethodInvocation"  
    
  8.     value="true">  
    
  9. </constant>  
    
  10. truts.enable.DynamicMethodInvocation = true,-动态方法调用,   
    
  11. 为true时,就可以在struts.xml配置“*”的通配符,来调用action里的方法   
    
  12. -->
  13. <!-- add package here extends="struts-default"-->  
    
  14. <package name="dongzi" extends="json-default"><!--需要将struts-default改为json-default-->  
    
  15.     <!-- setting action -->  
    
  16.     <action name="login" class="com.dongzi.action.LoginAction"  
    
  17.         method="login">  
    
  18.         <result type="json"></result>  
    
  19.         <!--返回值类型设置为json,不设置返回页面-->  
    
  20.     </action>  
    
  21. </package>  
    

看看这个action

<action name="login" class="com.dongzi.action.LoginAction"
        method="login">
        <result type="json"></result>
        <!--返回值类型设置为json,不设置返回页面-->
    </action>

返回的是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.        //   this.response.getWriter().write(json.toString());   
    
  26.         //{"username":"mingg","password":"123"}   
    
  27.     JSONObject json=new JSONObject();   
    
  28. // json.put("username", "mingg");

  29. // json.put("password","123");

  30.         //【这里在JSON中包含一个Map】   
    
  31.         Map map=new HashMap<Object, String>();   
    
  32.         map.put("username", "xiaomingg");   
    
  33.         map.put("password", "1234");   
    
  34.         map.put("state", "1");   
    
  35.         json.put("userbean", map);   
    
  36.         response.getWriter().write(json.toString());   
    
  37.         ////{"userbean":{"username":"100196","password":"1234453","State":1}}   
    
  38.        /**  
    
  39.         * 值的数组  
    
  40.         {"people": }  
    
  41.         */  
    
  42. // JSONArray jsonArray=new JSONArray();

  43. //

  44. // JSONObject json=new JSONObject();

  45. // json.put("username", "mingg");

  46. // json.put("password","123");

  47. // json.put("email", "172@qq.com");

  48. //

  49. // JSONObject json1=new JSONObject();

  50. // json1.put("username", "jie");

  51. // json1.put("password","111");

  52. // json1.put("email", "172@sina.com");

  53. //

  54. // JSONObject json2=new JSONObject();

  55. // json2.put("username", "yong");

  56. // json2.put("password","1232");

  57. // json2.put("email", "1sa@qq.com");

  58. //

  59. // jsonArray.add(0, json);

  60. // jsonArray.add(1, json1);

  61. // jsonArray.add(2, json2);

  62. //

  63. //

  64. // JSONObject alObject=new JSONObject();

  65. // alObject.put("people", jsonArray);

  66.         /***  
    
  67.          *{ "programmers":      ,  
    
  68.          *  "authors":    ,  
    
  69.          *  "musicians":   
    
  70.          * }  
    
  71.          *   
    
  72.          */  
    
  73. // JSONArray jsonArray=new JSONArray();

  74. //

  75. // JSONObject json=new JSONObject();

  76. // json.put("username", "mingg");

  77. // json.put("password","123");

  78. // json.put("email", "172@qq.com");

  79. //

  80. // JSONObject json1=new JSONObject();

  81. // json1.put("username", "jie");

  82. // json1.put("password","111");

  83. // json1.put("email", "172@sina.com");

  84. //

  85. // JSONObject json2=new JSONObject();

  86. // json2.put("username", "yong");

  87. // json2.put("password","1232");

  88. // json2.put("email", "1sa@qq.com");

  89. //

  90. // jsonArray.add(0, json);

  91. // jsonArray.add(1, json1);

  92. // jsonArray.add(2, json2);

  93. //

  94. //

  95. //

  96. // JSONArray jsonArray2=new JSONArray();

  97. //

  98. // JSONObject json20=new JSONObject();

  99. // json20.put("username", "mingg");

  100. // json20.put("password","123");

  101. // json20.put("genre", "science fiction");

  102. //

  103. // JSONObject json21=new JSONObject();

  104. // json21.put("username", "jie");

  105. // json21.put("password","111");

  106. // json21.put("genre", "fantasy");

  107. //

  108. // JSONObject json22=new JSONObject();

  109. // json22.put("username", "yong");

  110. // json22.put("password","1232");

  111. // json22.put("genre", "christian fiction");

  112. //

  113. // jsonArray2.add(0, json20);

  114. // jsonArray2.add(1, json21);

  115. // jsonArray2.add(2, json22);

  116. //

  117. //

  118. // JSONArray jsonArray3=new JSONArray();

  119. //

  120. // JSONObject json30=new JSONObject();

  121. // json30.put("username", "mingg");

  122. // json30.put("password","123");

  123. // json30.put("instrument", "guitar");

  124. //

  125. // JSONObject json31=new JSONObject();

  126. // json31.put("username", "jie");

  127. // json31.put("password","111");

  128. // json31.put("instrument", "piano");

  129. //

  130. // JSONObject json32=new JSONObject();

  131. // json32.put("username", "yong");

  132. // json32.put("password","1232");

  133. // json32.put("instrument", "flute");//笛

  134. //

  135. // jsonArray3.add(0, json30);

  136. // jsonArray3.add(1, json31);

  137. // jsonArray3.add(2, json32);

  138. //

  139. //

  140. // JSONObject alObject=new JSONObject();

  141. // alObject.put("programmers", jsonArray);

  142. // alObject.put("authors", jsonArray2);

  143. // alObject.put("musicians", jsonArray3);

  144.         /**  
    
  145.          * yong:1232:1sa@qq.com  
    
  146.          */  
    
  147.         //获取任意节点的值:试例,第个节点,第三个子节点   
    
  148. // JSONArray jsonArrayt11 = (JSONArray) alObject.get("programmers");

  149. //

  150. // JSONObject jsonObject11=(JSONObject)jsonArrayt11.get(2);

  151. //

  152. // String username=jsonObject11.getString("username");

  153. // String password=jsonObject11.getString("password");

  154. // String email=jsonObject11.getString("email");

  155. //

  156. // StringBuffer sBuffer=new StringBuffer();

  157. // sBuffer.append(username+":").append(password+":").append(email);

  158. // response.getWriter().write(username.toString());

  159.         /**  
    
  160.          * JSONObject json=new JSONObject(); json.put("login", "login");  
    
  161.          * response.setContentType("text/html;charset=utf-8");  
    
  162.          * System.out.println(json); byte jsonBytes =  
    
  163.          * json.toString().getBytes("utf-8");  
    
  164.          * response.setContentLength(jsonBytes.length);  
    
  165.          * response.getOutputStream().write(jsonBytes);  
    
  166.          */  
    
  167. // JSONObject json=new JSONObject();

  168. // json.put("login", "login");

  169. // byte jsonBytes = json.toString().getBytes("utf-8");

  170. // response.setContentType("text/html;charset=utf-8");

  171. // response.setContentLength(jsonBytes.length);

  172. // response.getOutputStream().write(jsonBytes);

  173. // response.getOutputStream().flush();

  174. // response.getOutputStream().close();

  175.     } catch (Exception e) {   
    
  176.         e.printStackTrace();   
    
  177.     }   
    
  178.     // return null;   
    
  179. }   
    
  180. }
    我下面简单说一下JSON解析过程。

    JSONObject json=new JSONObject();
      //【这里在JSON中包含一个Map】
      Map map=new HashMap<Object, String>();
    
      map.put("username", "xiaomingg");
      map.put("password", "1234");
      map.put("state", "1");
      json.put("userbean", map);
    
      response.getWriter().write(json.toString());
    

通过访问http://localhost:8888/AndroidServerApp/login.action,得到如下JSON数据:

服务器端的配置完成了。下面我来配置Android客户端了。

由于Android内置提拱了解析JSON数据的包。所以就不需要使用第三方包了

Android 访问网络资源的代码如下所示:

  1. private static String url = "http://10.0.2.2:8888/AndroidServerApp/login.action";   
    
  2. getPDAServerData(url);
  3. private void getPDAServerData(String url) {
  4.     HttpClient client = new DefaultHttpClient();   
    
  5.     //提拱默认的HttpClient实现   
    
  6.     HttpPost request;   
    
  7.     try {   
    
  8.         request = new HttpPost(new URI(url));   
    
  9.         HttpResponse response = client.execute(request);   
    
  10.         // 判断请求是否成功   
    
  11.         if (response.getStatusLine().getStatusCode() == 200) { //200表示请求成功   
    
  12.             HttpEntity entity = response.getEntity();   
    
  13.             if (entity != null) {   
    
  14.                 String out = EntityUtils.toString(entity);   
    
  15.                 JSONObject jsonObject;   
    
  16.                 String username = "";   
    
  17.                 String password = "";   
    
  18.                 String stateStr="";   
    
  19.                 UserBean userBean=new UserBean();   
    
  20.                 try {   
    
  21.                     //{"userbean":{"username":"100196","password":"1234453","State":1}}   
    
  22.                     //JSONObject jsonObject = new JSONObject(builder.toString()).getJSONObject("userbean");    
    
  23.                     jsonObject = new JSONObject(out).getJSONObject("userbean");   
    
  24.                     userBean.setUsername(jsonObject.getString("username"));   
    
  25.                     userBean.setPassword( jsonObject.getString("password"));   
    
  26.                     userBean.setState(Integer.parseInt(jsonObject.getString("state")));   
    
  27.                 } catch (JSONException e) {   
    
  28.                     // TODO Auto-generated catch block   
    
  29.                     e.printStackTrace();   
    
  30.                 }   
    
  31.                 new AlertDialog.Builder(this).setMessage(   
    
  32.                         userBean.getUsername() + ":" + userBean.getState()).create().show();   
    
  33.             }   
    
  34.         }   
    
  35.     } catch (URISyntaxException e) {   
    
  36.         e.printStackTrace();   
    
  37.         new AlertDialog.Builder(this).setMessage(e.getMessage()).create()   
    
  38.                 .show();   
    
  39.     } catch (ClientProtocolException e) {   
    
  40.         e.printStackTrace();   
    
  41.         new AlertDialog.Builder(this).setMessage(e.getMessage()).create()   
    
  42.                 .show();   
    
  43.     } catch (IOException e) {   
    
  44.         e.printStackTrace();   
    
  45.         new AlertDialog.Builder(this).setMessage(e.getMessage()).create()   
    
  46.                 .show();   
    
  47.     }   
    
  48. }  
    

里面的IP地址:10.0.2.2,代表着手机模拟器本地的地址,相当于localhost,但不能使用localhost,或者127.0.0.1,因不是在PC机上测试,而是在手机AVD上测试之。

而UserBean.java,它就是一个JAVABEAN,代码如下所示:

  1. package po;
  2. public class UserBean {
  3. private String username;   
    
  4. private String password;   
    
  5. private int state;   
    
  6. public String getUsername() {   
    
  7.     return username;   
    
  8. }   
    
  9. public void setUsername(String username) {   
    
  10.     this.username = username;   
    
  11. }   
    
  12. public String getPassword() {   
    
  13.     return password;   
    
  14. }   
    
  15. public void setPassword(String password) {   
    
  16.     this.password = password;   
    
  17. }   
    
  18. public int getState() {   
    
  19.     return state;   
    
  20. }   
    
  21. public void setState(int state) {   
    
  22.     this.state = state;   
    
  23. }   
    
  24. }

注恴必须AndroidManifest.xml中加入如下代码,不然Android就不能访问web资源。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。