您的位置:首页 > 理论基础 > 计算机网络

android网络编程

2014-02-17 14:25 197 查看
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. <!-- 定义Struts2的核心控制器:FilterDispatcher --> 

   2.   <filter> 

   3.      <!-- 定义核心Filter的名称 --> 

   4.      <filter-name>struts2</filter-name> 

   5.      <!-- 定义Filter的实现类 --> 

   6.      <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> 

   7.   </filter> 

   8.     

   9.   <filter-mapping> 

  10.      <filter-name>struts2</filter-name> 

  11.      <url-pattern>/*</url-pattern> 

  12.   </filter-mapping> 

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

   1. <?xml version="1.0" encoding="UTF-8"?> 

   2. <!DOCTYPE struts PUBLIC  

   3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  

   4. "http://struts.apache.org/dtds/struts-2.0.dtd"> 

   5. <struts> 

   6.     <!-- setting encoding,DynamicMethod,language  

   7.         <constant name="struts.custom.i18n.resources" value="messageResource"></constant> 

   8.     --> 

   9.     <constant name="struts.i18n.encoding" value="UTF-8"></constant> 

  10.     <constant name="struts.enable.DynamicMethodInvocation" 

  11.         value="true"> 

  12.     </constant> 

  13. <!--   

  14.     truts.enable.DynamicMethodInvocation = true,-动态方法调用,  

  15.     为true时,就可以在struts.xml配置“*”的通配符,来调用action里的方法  

  16.  --> 

  17.     <!-- add package here extends="struts-default"--> 

  18.     <package name="dongzi" extends="json-default"><!--需要将struts-default改为json-default--> 

  19.         <!-- setting action --> 

  20.         <action name="login" class="com.dongzi.action.LoginAction" 

  21.             method="login"> 

  22.             <result type="json"></result> 

  23.             <!--返回值类型设置为json,不设置返回页面--> 

  24.         </action> 

  25.     </package> 

  26. </struts> 

看看这个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.               

  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<Object, String>();  

  37.             map.put("username", "xiaomingg");  

  38.             map.put("password", "1234");  

  39.             map.put("state", "1");  

  40.             json.put("userbean", map);  

  41.               

  42.             response.getWriter().write(json.toString());  

  43.             ////{"userbean":{"username":"100196","password":"1234453","State":1}}  

  44.               

  45.               

  46.            /** 

  47.             * 值的数组 

  48.              

  49.             {"people": [ 

  50.                 {"username":"mingg","password":"123","email":"172@qq.com"}, 

  51.                  

  52.                 {"username":"jie","password":"111","email":"172@sina.com"}, 

  53.                  

  54.                 {"username":"yong","password":"1232","email":"1sa@qq.com"} 

  55.             ]} 

  56.              

  57.             */ 

  58.               

  59.               

  60.               

  61. //          JSONArray jsonArray=new JSONArray();  

  62. //            

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

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

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

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

  67. //            

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

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

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

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

  72. //            

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

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

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

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

  77. //            

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

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

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

  81. //            

  82. //            

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

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

  85.               

  86.               

  87.               

  88.             /*** 

  89.              *{ "programmers":      [ 

  90.              *     {"username":"mingg","password":"123","email":"172@qq.com"}, 

  91.              *      

  92.              *     {"username":"jie","password":"111","email":"172@sina.com"}, 

  93.              *      

  94.              *     {"username":"yong","password":"1232","email":"1sa@qq.com"}], 

  95.              *  "authors":    [ 

  96.              *      {"username":"mingg","password":"123","genre":"science fiction"}, 

  97.              *  

  98.              *      {"username":"jie","password":"111","genre":"fantasy"}, 

  99.              *  

100.              *      {"username":"yong","pa
d5ef
ssword":"1232","genre":"christian fiction"}], 

101.              *  "musicians": [ 

102.              *      {"username":"mingg","password":"123","instrument":"guitar"}, 

103.              *  

104.              *      {"username":"jie","password":"111","instrument":"piano"}, 

105.              *  

106.              *      {"username":"yong","password":"1232","instrument":"flute"}] 

107.              * } 

108.              *  

109.              */ 

110.               

111.               

112. //          JSONArray jsonArray=new JSONArray();  

113. //            

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

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

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

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

118. //            

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

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

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

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

123. //            

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

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

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

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

128. //            

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

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

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

132. //            

133. //            

134. //            

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

136. //            

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

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

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

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

141. //            

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

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

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

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

146. //            

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

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

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

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

151. //            

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

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

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

155. //            

156. //            

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

158. //            

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

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

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

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

163. //            

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

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

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

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

168. //            

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

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

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

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

173. //            

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

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

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

177. //            

178. //            

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

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

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

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

183.               

184.               

185.             /** 

186.              * yong:1232:1sa@qq.com 

187.              */ 

188.             //获取任意节点的值:试例,第个节点,第三个子节点  

189.               

190. //          JSONArray jsonArrayt11 = (JSONArray) alObject.get("programmers");  

191. //            

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

193. //            

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

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

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

197. //            

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

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

200.               

201.               

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

203.               

204.               

205.               

206.               

207.             /** 

208.              * JSONObject json=new JSONObject(); json.put("login", "login"); 

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

210.              * System.out.println(json); byte[] jsonBytes = 

211.              * json.toString().getBytes("utf-8"); 

212.              * response.setContentLength(jsonBytes.length); 

213.              * response.getOutputStream().write(jsonBytes); 

214.              */ 

215.               

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

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

218. //            byte[] jsonBytes = json.toString().getBytes("utf-8");  

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

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

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

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

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

224.               

225.         } catch (Exception e) {  

226.             e.printStackTrace();  

227.         }  

228.         // return null;  

229.     }  

230. } 

我下面简单说一下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.                       

  20.                     UserBean userBean=new UserBean();  

  21.                     try {  

  22.               

  23.                         //{"userbean":{"username":"100196","password":"1234453","State":1}}  

  24.                         //JSONObject jsonObject = new JSONObject(builder.toString()).getJSONObject("userbean");   

  25.                       

  26.                         jsonObject = new JSONObject(out).getJSONObject("userbean");  

  27.                           

  28.                           

  29.                         userBean.setUsername(jsonObject.getString("username"));  

  30.                         userBean.setPassword( jsonObject.getString("password"));  

  31.                         userBean.setState(Integer.parseInt(jsonObject.getString("state")));  

  32.                           

  33.                           

  34.                           

  35.                     } catch (JSONException e) {  

  36.                         // TODO Auto-generated catch block  

  37.                         e.printStackTrace();  

  38.                     }  

  39.                     new AlertDialog.Builder(this).setMessage(  

  40.                             userBean.getUsername() + ":" + userBean.getState()).create().show();  

  41.                 }  

  42.             }  

  43.         } catch (URISyntaxException e) {  

  44.             e.printStackTrace();  

  45.             new AlertDialog.Builder(this).setMessage(e.getMessage()).create()  

  46.                     .show();  

  47.         } catch (ClientProtocolException e) {  

  48.             e.printStackTrace();  

  49.             new AlertDialog.Builder(this).setMessage(e.getMessage()).create()  

  50.                     .show();  

  51.         } catch (IOException e) {  

  52.             e.printStackTrace();  

  53.             new AlertDialog.Builder(this).setMessage(e.getMessage()).create()  

  54.                     .show();  

  55.         }  

  56.     } 

里面的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资源。

   1. <uses-permission Android:name="android.permission.INTERNET" />   

转自http://www.linuxidc.com/Linux/2011-04/35009.htm 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: