您的位置:首页 > 编程语言 > Java开发

Android与Struts2简单json通信

2016-01-25 14:37 567 查看
具体要求是:

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

闲话不多说,直接上代码

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

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: