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文件,代码如下所示:
<!-- 定义Struts2的核心控制器:FilterDispatcher --> <filter> <!-- 定义核心Filter的名称 --> <filter-name>struts2</filter-name> <!-- 定义Filter的实现类 --> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
添加完JAR包后。我们来配置一下struts.xml文件,这个文件存放在src根目录下面,代码如下所示:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- setting encoding,DynamicMethod,language <constant name="struts.custom.i18n.resources" value="messageResource"></constant> --> <constant name="struts.i18n.encoding" value="UTF-8"></constant> <constant name="struts.enable.DynamicMethodInvocation" value="true"> </constant> <!-- truts.enable.DynamicMethodInvocation = true,-动态方法调用, 为true时,就可以在struts.xml配置“*”的通配符,来调用action里的方法 --> <!-- add package here extends="struts-default"--> <package name="dongzi" extends="json-default"><!--需要将struts-default改为json-default--> <!-- setting action --> <action name="login" class="com.dongzi.action.LoginAction" method="login"> <result type="json"></result> <!--返回值类型设置为json,不设置返回页面--> </action> </package> </struts>
看看这个action
<action name="login" class="com.dongzi.action.LoginAction"
method="login">
<result type="json"></result>
<!--返回值类型设置为json,不设置返回页面-->
</action>
返回的是json 数据。而且是由LoginAction类去处理,它存放在com.dongzi.action下面。LoginAction类的代码如下:
public class LoginAction extends ActionSupport implements ServletRequestAware, ServletResponseAware { /** * */ private static final long serialVersionUID = 1L; HttpServletRequest request; HttpServletResponse response; public void setServletRequest(HttpServletRequest request) { this.request = request; } public void setServletResponse(HttpServletResponse response) { this.response = response; } public void login() { try { // HttpServletRequest request =ServletActionContext.getRequest(); // HttpServletResponse response=ServletActionContext.getResponse(); this.response.setContentType("text/html;charset=utf-8"); this.response.setCharacterEncoding("UTF-8"); // 将要返回的实体对象进行json处理 // JSONObject json=JSONObject.fromObject(this.getUsername()); // 输出格式如:{"id":1, "username":"zhangsan", "pwd":"123"} // System.out.println(json); // this.response.getWriter().write(json.toString()); //{"username":"mingg","password":"123"} JSONObject json=new JSONObject(); // json.put("username", "mingg"); // json.put("password","123"); //【这里在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()); ////{"userbean":{"username":"100196","password":"1234453","State":1}} /** * 值的数组 {"people": [ {"username":"mingg","password":"123","email":"[email protected]"}, {"username":"jie","password":"111","email":"[email protected]"}, {"username":"yong","password":"1232","email":"[email protected]"} ]} */ // JSONArray jsonArray=new JSONArray(); // // JSONObject json=new JSONObject(); // json.put("username", "mingg"); // json.put("password","123"); // json.put("email", "[email protected]"); // // JSONObject json1=new JSONObject(); // json1.put("username", "jie"); // json1.put("password","111"); // json1.put("email", "[email protected]"); // // JSONObject json2=new JSONObject(); // json2.put("username", "yong"); // json2.put("password","1232"); // json2.put("email", "[email protected]"); // // jsonArray.add(0, json); // jsonArray.add(1, json1); // jsonArray.add(2, json2); // // // JSONObject alObject=new JSONObject(); // alObject.put("people", jsonArray); /*** *{ "programmers": [ * {"username":"mingg","password":"123","email":"[email protected]"}, * * {"username":"jie","password":"111","email":"[email protected]"}, * * {"username":"yong","password":"1232","email":"[email protected]"}], * "authors": [ * {"username":"mingg","password":"123","genre":"science fiction"}, * * {"username":"jie","password":"111","genre":"fantasy"}, * * {"username":"yong","password":"1232","genre":"christian fiction"}], * "musicians": [ * {"username":"mingg","password":"123","instrument":"guitar"}, * * {"username":"jie","password":"111","instrument":"piano"}, * * {"username":"yong","password":"1232","instrument":"flute"}] * } * */ // JSONArray jsonArray=new JSONArray(); // // JSONObject json=new JSONObject(); // json.put("username", "mingg"); // json.put("password","123"); // json.put("email", "[email protected]"); // // JSONObject json1=new JSONObject(); // json1.put("username", "jie"); // json1.put("password","111"); // json1.put("email", "[email protected]"); // // JSONObject json2=new JSONObject(); // json2.put("username", "yong"); // json2.put("password","1232"); // json2.put("email", "[email protected]"); // // jsonArray.add(0, json); // jsonArray.add(1, json1); // jsonArray.add(2, json2); // // // // JSONArray jsonArray2=new JSONArray(); // // JSONObject json20=new JSONObject(); // json20.put("username", "mingg"); // json20.put("password","123"); // json20.put("genre", "science fiction"); // // JSONObject json21=new JSONObject(); // json21.put("username", "jie"); // json21.put("password","111"); // json21.put("genre", "fantasy"); // // JSONObject json22=new JSONObject(); // json22.put("username", "yong"); // json22.put("password","1232"); // json22.put("genre", "christian fiction"); // // jsonArray2.add(0, json20); // jsonArray2.add(1, json21); // jsonArray2.add(2, json22); // // // JSONArray jsonArray3=new JSONArray(); // // JSONObject json30=new JSONObject(); // json30.put("username", "mingg"); // json30.put("password","123"); // json30.put("instrument", "guitar"); // // JSONObject json31=new JSONObject(); // json31.put("username", "jie"); // json31.put("password","111"); // json31.put("instrument", "piano"); // // JSONObject json32=new JSONObject(); // json32.put("username", "yong"); // json32.put("password","1232"); // json32.put("instrument", "flute");//笛 // // jsonArray3.add(0, json30); // jsonArray3.add(1, json31); // jsonArray3.add(2, json32); // // // JSONObject alObject=new JSONObject(); // alObject.put("programmers", jsonArray); // alObject.put("authors", jsonArray2); // alObject.put("musicians", jsonArray3); /** * yong:1232:[email protected] */ //获取任意节点的值:试例,第个节点,第三个子节点 // JSONArray jsonArrayt11 = (JSONArray) alObject.get("programmers"); // // JSONObject jsonObject11=(JSONObject)jsonArrayt11.get(2); // // String username=jsonObject11.getString("username"); // String password=jsonObject11.getString("password"); // String email=jsonObject11.getString("email"); // // StringBuffer sBuffer=new StringBuffer(); // sBuffer.append(username+":").append(password+":").append(email); // response.getWriter().write(username.toString()); /** * JSONObject json=new JSONObject(); json.put("login", "login"); * response.setContentType("text/html;charset=utf-8"); * System.out.println(json); byte[] jsonBytes = * json.toString().getBytes("utf-8"); * response.setContentLength(jsonBytes.length); * response.getOutputStream().write(jsonBytes); */ // JSONObject json=new JSONObject(); // json.put("login", "login"); // byte[] jsonBytes = json.toString().getBytes("utf-8"); // response.setContentType("text/html;charset=utf-8"); // response.setContentLength(jsonBytes.length); // response.getOutputStream().write(jsonBytes); // response.getOutputStream().flush(); // response.getOutputStream().close(); } catch (Exception e) { e.printStackTrace(); } // return null; } }
我下面简单说一下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 访问网络资源的代码如下所示:
private static String url = "http://10.0.2.2:8888/AndroidServerApp/login.action"; getPDAServerData(url); private void getPDAServerData(String url) { HttpClient client = new DefaultHttpClient(); //提拱默认的HttpClient实现 HttpPost request; try { request = new HttpPost(new URI(url)); HttpResponse response = client.execute(request); // 判断请求是否成功 if (response.getStatusLine().getStatusCode() == 200) { //200表示请求成功 HttpEntity entity = response.getEntity(); if (entity != null) { String out = EntityUtils.toString(entity); JSONObject jsonObject; String username = ""; String password = ""; String stateStr=""; UserBean userBean=new UserBean(); try { //{"userbean":{"username":"100196","password":"1234453","State":1}} //JSONObject jsonObject = new JSONObject(builder.toString()).getJSONObject("userbean"); jsonObject = new JSONObject(out).getJSONObject("userbean"); userBean.setUsername(jsonObject.getString("username")); userBean.setPassword( jsonObject.getString("password")); userBean.setState(Integer.parseInt(jsonObject.getString("state"))); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } new AlertDialog.Builder(this).setMessage( userBean.getUsername() + ":" + userBean.getState()).create().show(); } } } catch (URISyntaxException e) { e.printStackTrace(); new AlertDialog.Builder(this).setMessage(e.getMessage()).create() .show(); } catch (ClientProtocolException e) { e.printStackTrace(); new AlertDialog.Builder(this).setMessage(e.getMessage()).create() .show(); } catch (IOException e) { e.printStackTrace(); new AlertDialog.Builder(this).setMessage(e.getMessage()).create() .show(); } }
里面的IP地址:10.0.2.2,代表着手机模拟器本地的地址,相当于localhost,但不能使用localhost,或者127.0.0.1,因不是在PC机上测试,而是在手机AVD上测试之。
而UserBean.java,它就是一个JAVABEAN,代码如下所示:
package po; public class UserBean { private String username; private String password; private int state; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getState() { return state; } public void setState(int state) { this.state = state; } }
注恴必须AndroidManifest.xml中加入如下代码,不然Android就不能访问web资源。
<uses-permission android:name="android.permission.INTERNET" />
最终得到如下界面:
更多相关文章
- 【移动开发】Android应用程序中实用的代码框架(一)
- 我的Android NDK之旅(五),在Mac上用eclipse手动编写代码向android开
- android开源代码
- Android 混淆代码学习以及Android加密工具--APKProtect的使用
- android代码实现免提功能
- CentOS 下载 Android 源代码。