具体要求是:

服务器端得到客户端传递来的数据,并返回给客户端一条json格式的字符串

闲话不多说,直接上代码

首先是服务器端代码:建立一个web工程,导入struts2和json的jar包,并在web.xml中引入struts2

Android与Struts2简单json通信-LMLPHP

 <?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     id="WebApp_ID" version="3.1">
     <display-name>StrutsForAndroid</display-name>
     <!-- 配置过滤器(即在web中添加struts2) -->
     <filter>
         <filter-name>struts2</filter-name>
         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
         <!-- 配置后缀 <init-param> <param-name>struts.action.extension</param-name>
             <param-value>do,html</param-value> </init-param> -->
     </filter>
     <filter-mapping>
         <filter-name>struts2</filter-name>
         <url-pattern>/*</url-pattern>
     </filter-mapping>

     <welcome-file-list>
         <welcome-file>index.jsp</welcome-file>
     </welcome-file-list>
 </web-app>

web.xml

然后就是java代码啦

Android与Struts2简单json通信-LMLPHP

 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE struts PUBLIC
     "-//Apache Software Foundation//DTD Struts Configuration//EN"
     "http://struts.apache.org/dtds/struts-2.3.dtd">
 <struts>

     <package name="androidService" namespace="/androidService"
         extends="struts-default">
         <action name="getMessage" class="com.wzy.andriod.actions.AndroidService"
             method="getMsg">
             <result></result>
         </action>
     </package>

     <package name="androidJsonService" namespace="/androidJsonService"
         extends="struts-default">
         <action name="*" class="com.wzy.andriod.actions.AndroidService" method="{1}">
             <result ></result>
         </action>
     </package>

 </struts>

androidService.xml

 package com.wzy.andriod.actions;

 import java.io.PrintWriter;

 import net.sf.json.JSONArray;
 import net.sf.json.JSONObject;

 public class AndroidService extends SuperAction {

     private static final long serialVersionUID = 1L;

     public void getMsg() {

         System.out.println("开始-->");
         try {
             String name = request.getParameter("name");
             System.out.println(name);

             response.setCharacterEncoding("utf-8");
             response.setContentType("text/html");
             PrintWriter writer = response.getWriter();
             writer.print("get到了");

         } catch (Exception e) {
             e.printStackTrace();
         }
     }

     public void getJson() {
         // http://localhost:8080/StrutsForAndroid/androidJsonService/getJson
         System.out.println("getJson开始-->");

         try {
             request.setCharacterEncoding("UTF-8");
             String name = request.getParameter("name");
             String passwd = request.getParameter("passwd");
             System.out.println("-->"+name);
             System.out.println("-->"+passwd);
             JSONArray jsonArray = new JSONArray();

             JSONObject jsonObject = new JSONObject();
             jsonObject.put("id", 1);
             jsonObject.put("name", "小明");
             jsonObject.put("age", 23);

             JSONObject jsonObject1 = new JSONObject();
             jsonObject1.put("id", 2);
             jsonObject1.put("name", "小红");
             jsonObject1.put("age", 12);

             JSONObject jsonObject2 = new JSONObject();
             jsonObject2.put("id", 3);
             jsonObject2.put("name", "Jack");
             jsonObject2.put("age", 100);

             jsonArray.add(0, jsonObject);
             jsonArray.add(1, jsonObject1);
             jsonArray.add(2, jsonObject2);

             response.setCharacterEncoding("UTF-8");
             response.setContentType("text/html");
             PrintWriter writer = response.getWriter();
             // System.out.println(jsonArray.toString());
             writer.print(jsonArray.toString());
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
 }

AndroidService.java

 package com.wzy.andriod.actions;

 import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;

 import org.apache.struts2.interceptor.ServletRequestAware;
 import org.apache.struts2.interceptor.ServletResponseAware;
 import org.apache.struts2.util.ServletContextAware;

 import com.opensymphony.xwork2.ActionSupport;

 //所有的action动作的父类
 public class SuperAction extends ActionSupport implements ServletRequestAware,
         ServletResponseAware, ServletContextAware {

     private static final long serialVersionUID = 1L;
     /*serialVersionUID作用是序列化时保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。*/
     protected HttpServletRequest request;
     protected HttpServletResponse response;
     protected ServletContext application;
     protected HttpSession session;

     @Override
     public void setServletContext(ServletContext application) {
         this.application = application;
     }

     @Override
     public void setServletResponse(HttpServletResponse response) {
         this.response = response;
     }

     @Override
     public void setServletRequest(HttpServletRequest request) {
         this.request = request;
         this.session = this.request.getSession();
     }

 }

SuperAction.java

 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE struts PUBLIC
     "-//Apache Software Foundation//DTD Struts Configuration//EN"
     "http://struts.apache.org/dtds/struts-2.3.dtd">
 <struts>
     <package name="default" namespace="/" extends="struts-default">
     </package>

     <include file="com/struts2/files/androidService.xml"></include>

 </struts>

struts.xml  

开启tomcat服务器后,通过浏览器访问是如下效果

Android与Struts2简单json通信-LMLPHP

后台打印结果

Android与Struts2简单json通信-LMLPHP

以上就是服务端代码部署情况,接下来是安卓客户端代码

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.strutsclient"
     android:versionCode="1"
     android:versionName="1.0" >

     <uses-sdk
         android:minSdkVersion="8"
         android:targetSdkVersion="18" />

     <application
         android:allowBackup="true"
         android:icon="@drawable/ic_launcher"
         android:label="@string/app_name"
         android:theme="@style/AppTheme" >
         <activity
             android:name="com.example.strutsclient.MainActivity"
             android:label="@string/app_name" >
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />

                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
     </application>
 <uses-permission android:name="android.permission.INTERNET"/>
 </manifest>

AndroidManifest.xml

layout中建立一个用户登录界面

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical" >

     <EditText
         android:id="@+id/name"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:ems="10"
         android:text="123">
     </EditText>

     <EditText
         android:id="@+id/passwd"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="123"
         android:ems="10" />

     <Button
         android:id="@+id/login"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="确定" />

 </LinearLayout>

userlogin.xml

然后就是java代码啦

 package com.example.strutsclient;

 import java.io.BufferedReader;
 import java.io.InputStream;

 import java.io.InputStreamReader;
 import java.net.HttpURLConnection;
 import java.net.URL;

 import android.util.Log;

 public class HttpDownloader {

     public String download(String urlStr) {
         StringBuffer sb = new StringBuffer();
         String line = null;
         BufferedReader buffer = null;
         try {
             URL url = new URL(urlStr);// 创建url对象
             HttpURLConnection urlConn = (HttpURLConnection) url
                     .openConnection();// 创建http链接
             Log.i("---->", "----11----");
             InputStream stream = urlConn.getInputStream();
             Log.i("---->", "----22----");
             buffer = new BufferedReader(new InputStreamReader(stream));// io流
             Log.i("---->", "----33----");
             while ((line = buffer.readLine()) != null) {
                 sb.append(line);
             }
         } catch (Exception e) {
             Log.i("---->", e.toString());
             e.printStackTrace();
             return "wrong";
         } finally {
             try {
                 buffer.close();
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }
         return sb.toString();
     }

 }

HttpDownloader.java

 package com.example.strutsclient;

 import android.os.Build;
 import android.os.Bundle;
 import android.os.StrictMode;
 import android.annotation.SuppressLint;
 import android.annotation.TargetApi;
 import android.app.Activity;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.Toast;

 @TargetApi(Build.VERSION_CODES.GINGERBREAD)
 @SuppressLint("NewApi")
 public class MainActivity extends Activity {

     EditText name;
     EditText passwd;
     Button login;

     String sname;
     String spasswd;

     @TargetApi(Build.VERSION_CODES.GINGERBREAD)
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.userlogin);
         // 防止android.os.NetworkOnMainThreadException,可使用异步加载或者加入以下代码
         // 因为访问网络会消耗很长时间,安卓会认为死机了,所有出现异常
         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads().detectDiskWrites().detectNetwork()
                 .penaltyLog().build());
         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                 .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                 .penaltyLog().penaltyDeath().build());

         this.name = (EditText) super.findViewById(R.id.name);
         this.passwd = (EditText) super.findViewById(R.id.passwd);
         this.login = (Button) super.findViewById(R.id.login);
         // Toast.makeText(this, name.getText(), Toast.LENGTH_SHORT).show();

         login.setOnClickListener(new OnClickListener() {
             @Override
             public void onClick(View arg0) {
                 sname = name.getText().toString();
                 spasswd = passwd.getText().toString();
                 HttpDownloader downloader = new HttpDownloader();
                 String url = "http://172.22.0.1:8080/StrutsForAndroid/androidJsonService/getJson?name="
                         + sname + "&passwd=" + spasswd;
                 String msg = downloader.download(url);
                 // Toast.makeText(this, url, Toast.LENGTH_SHORT).show();

                 login.setText(msg);
             }
         });
     }

 }

MainActivity.java

response发送不同类型的数据:

public static void writeJson(HttpServletResponse response, String text) {
  render(response, "application/json;charset=UTF-8", text);
}

public static void writeXml(HttpServletResponse response, String text) {
  render(response, "text/xml;charset=UTF-8", text);
}

public static void writeText(HttpServletResponse response, String text) {
  render(response, "text/plain;charset=UTF-8", text);
}

public static void render(HttpServletResponse response, String contentType,
String text) {
  response.setContentType(contentType);
  response.setHeader("Pragma", "No-cache");
  response.setHeader("Cache-Control", "no-cache");
  response.setDateHeader("Expires", 0);
try {
  response.getWriter().write(text);
} catch (IOException e) {
  //log.error(e.getMessage(), e);
}
}

05-11 11:13
查看更多