最近在学习Android,遇到Android端与服务器Struts2端的通信问题,弄了好久,现把他贴出来,大家一起学习

服务器端代码:

Action类:一定要给传送的属性写get,set方法,就是通过他struts才能识别到json关键字,并且把值传进来
public class LoginAndroid extends ActionSupport implements ServletRequestAware,ServletResponseAware{

private String result;//登陆身份
private String username;//登陆名
private String password;//登陆密码
@Autowired
private LoginService loginService;//登陆操作Service

/**
* 登录Android执行方法
* 
* @return
*/
public String execute()
{
System.out.println("进入  LoginAndroid:"+this.getUsername());
System.out.println("进入  LoginAndroid password:"+this.getPassword());

System.out.println("login Android");
result = loginService.checkBuyerLogin(username, password);
if (!result.equals("error"))
{
result = "success";
}
System.out.println(result);
return SUCCESS;
}
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 String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
 }struts配置:
<package name="AndroidDefault" namespace="/" extends="json-default">
<action name="loginAndroid" class="com.xmu.bst.vegegarden.Android.LoginAndroid">
<result name="success" type="json">
<param name="includeProperties">result</param>
</result>
</action>
</package>一定要记得,package的extends="json-default",这点很重要,以及result的type为json
Android端:
username = mUser.getText().toString();
 password = mPassword.getText().toString();
     
 HttpTask task = new HttpTask(Login.this);
 task.setCallback(Login.this);
task.execute(Util.URL + Util.Login+"?username="+username+"&password="+password);这句话传的是服务器端的url,因为我想传两个参数,可是怎么都不成功,只能通过把,所有的url补全的方式,有大神,有更好的方式,还望赐教
以下为三个封装类,调用即可
import android.app.Dialog;
 import android.app.ProgressDialog;
 import android.content.Context;
 import android.os.AsyncTask;


/*在开发Android应用时必须遵守单线程模型的原则: Android UI操作并不是线程安全的
并且这些操作必须在UI线程中执行。在单线程模型中始终要记住两条法则:
1. 不要阻塞UI线程
2. 确保只在UI线程中访问Android UI工具包
      当一个程序第一次启动时,Android会同时启动一个对应的主线程(Main Thread),
      主线程主要负责处理与UI相关的事件,如:用户的按键事件,
,并把相关的事件分发到对应的组件进行处理。所以主线程通常又被叫做UI线程。
android提供了几种在其他线程中访问UI线程的方法。这些类或方法同样会使你的代码很复杂很难理解。然而当你需要实现一些很复杂的操作并需要频繁地更新UI时这会变得更糟糕。


     为了解决这个问题,Android 1.5提供了一个工具类:AsyncTask,
     它使创建需要与用户界面交互的长时间运行的任务变得更简单。
     相对来说AsyncTask更轻量级一些,适用于简单的异步处理,不需要借助线程和Handler
     即可实现。 

*
  */


 /*Params 启动任务执行的输入参数,比如HTTP请求的URL。
 Progress 后台任务执行的百分比。
 Result 后台执行任务最终返回的结果,比如String。*/


 public class HttpTask extends AsyncTask<String, Void, Void> {
protected String response;
protected HttpCallBack callback;

private HttpHelper httpHelper;


private ProgressDialog progressDialog = null;


public HttpTask(Context context) {
super();
httpHelper = new HttpHelper();
// 启动提示
progressDialog = ProgressDialog.show(context, "请稍后。。。", "获取资源中。。。",
true, true);


}


public void setCallback(HttpCallBack callback) {
this.callback = callback;
}


/**
* 后台运行主体
*/
@Override
protected Void doInBackground(String... params) {
//String... params不清楚参数几个的时候用
if (params.length > 1) {
response = httpHelper.postPage(params[0], params[1]);
} else {
response = httpHelper.postPage(params[0], null);
}
return null;
}





/**
* 当线程结束时
*/
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
if (callback != null) {
callback.callback(response);
}
}
 }import org.apache.http.HttpResponse;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.client.params.ClientPNames;
 import org.apache.http.client.params.CookiePolicy;
 import org.apache.http.entity.StringEntity;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.protocol.BasicHttpContext;
 import org.apache.http.protocol.HttpContext;
 import org.apache.http.util.EntityUtils;


 import android.content.Context;
 import android.util.Log;


 public class HttpHelper {
private DefaultHttpClient httpClient;//android中使用DefaultHttpClient访问
private HttpContext localContext;//在处理请求执行链的各个阶段中,会有一个对象在各个对象之间进行传递,也即会保存请求的上下文信息
private HttpResponse response;
private HttpPost httpPost;
// private Context context;
private String ret;


// private boolean abort = false;


public HttpHelper() {
httpClient = new DefaultHttpClient();
localContext = new BasicHttpContext();
}





public String postPage(String url, String data) {
ret = null;
data = data == null ? "" : data;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
CookiePolicy.RFC_2109);//RFC_2109是支持较普遍的一个,还有其他cookie协议  
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;// 字符串数据
httpPost.setHeader(
"User-Agent",
"Mozilla/5.0 (X11; U; Linux "
+ "i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpPost.setHeader(
"Accept",
"text/html,application/xml,"
+ "application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");


try {
tmp = new StringEntity(data, "UTF-8");


httpPost.setEntity(tmp);


response = httpClient.execute(httpPost, localContext);


if ((response != null) && (response.getEntity() != null)) {
ret = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
// TODO: handle exception
}
return ret;
}
 } public interface HttpCallBack {
void callback(String respone);
 }