笔者以前是学的Java EE,由于项目需要要开发Android,所以临时补了一个多星期,主要是手机端和服务器端交互,双向开发的。
首先在服务器端,我采用的是SSH框架,struts 2集合了JSON插件,服务器和客户端的信息交互采用的JSON来传输,由于在服务器端用了Struts 2,所以我就用装了一个JSON插件。这样,很轻易的就把服务器端的信息用JSON的形式发送到了手机端。以下是代码:
首先,在服务器端搭建好SSH框架,具体细节就不在陈述。struts.xml配置如下:
"login"extends="json-default"> "login"class="com.jclick.test.LoginAction"method="login"> "json"> "includeProperties">result - package>
-
"login"extends="json-default"> -
"login"class="com.jclick.test.LoginAction"method="login"> -
"json"> "includeProperties">result - package>
手机端的代码如下:
首先,手机端有一个缓存类,主要用于缓存一些手机端需要访问的数据,这样的好处是可以达达节省手机和服务器的交互,用单例实现的:
- packagecom.jclick.cache;
- importcom.jclick.bean.User;
- publicclassCache{
- privateUserUser;
- privateCache(){
- }
- /**构造单例*/
- privatestaticclassCacheHolder{
- privatestaticfinalCacheINSTANCE=newCache();
- }
- publicCachegetInstance(){
- returnCacheHolder.INSTANCE;
- }
- publicUsergetUser(){
- returnUser;
- }
- publicvoidsetUser(UserUser){
- this.User=User;
- }
- }
- packagecom.jclick.cache;
- importcom.jclick.bean.User;
- publicclassCache{
- privateUserUser;
- privateCache(){
- }
- /**构造单例*/
- privatestaticclassCacheHolder{
- privatestaticfinalCacheINSTANCE=newCache();
- }
- publicCachegetInstance(){
- returnCacheHolder.INSTANCE;
- }
- publicUsergetUser(){
- returnUser;
- }
- publicvoidsetUser(UserUser){
- this.User=User;
- }
- }
接着开始书写手机端的协议,用户向服务器发送请求,同时服务器反馈给手机端信息的:
- packagecom.jclick.protocol;
- importjava.io.BufferedReader;
- importjava.io.InputStreamReader;
- importjava.util.ArrayList;
- importjava.util.List;
- importorg.apache.http.HttpResponse;
- importorg.apache.http.NameValuePair;
- importorg.apache.http.client.HttpClient;
- importorg.apache.http.client.entity.UrlEncodedFormEntity;
- importorg.apache.http.client.methods.HttpPost;
- importorg.apache.http.impl.client.DefaultHttpClient;
- importorg.apache.http.message.BasicNameValuePair;
- importorg.json.JSONException;
- importorg.json.JSONObject;
- publicclassBaseProtocol{
- privateStringBuildersb=newStringBuilder();
- privateHttpClienthttpClient;
- privateHttpPosthttpRequest;
- privateHttpResponseresponse;
- privateList
nameValuePair=newArrayList (); - BaseProtocol(){
- httpClient=newDefaultHttpClient();
- }
- /**
- *向服务器端发送请求
- *
- *@paramurl
- *@throw***ception
- */
- protectedvoidpack(Stringurl)throw***ception{
- httpClient=newDefaultHttpClient();
- httpRequest=newHttpPost(url);
- httpRequest.setEntity(newUrlEncodedFormEntity(nameValuePair));
- response=httpClient.execute(httpRequest);
- }
- /**
- *得到返回数据
- *
- *@paramurl
- *@return
- *@throw***ception
- */
- protectedvoidparse()throw***ception{
- //TODO状态处理500200
- if(response.getStatusLine().getStatusCode()==200){
- BufferedReaderbufferedReader2=newBufferedReader(
- newInputStreamReader(response.getEntity().getContent()));
- for(Strings=bufferedReader2.readLine();s!=null;s=bufferedReader2
- .readLine()){
- sb.append(s);
- }
- }
- }
- /**
- *向服务器发送信息
- *
- *@paramkey
- *@paramvalue
- */
- publicvoidaddNameValuePair(Stringkey,Stringvalue){
- nameValuePair.add(newBasicNameValuePair(key,value));
- }
- /**
- *返回JSONObject对象数据模型
- *
- *@return
- *@throwsJSONException
- */
- publicJSONObjectgetJSON()throwsJSONException{
- returnnewJSONObject(sb.toString());
- }
- }
- packagecom.jclick.protocol;
- importjava.io.BufferedReader;
- importjava.io.InputStreamReader;
- importjava.util.ArrayList;
- importjava.util.List;
- importorg.apache.http.HttpResponse;
- importorg.apache.http.NameValuePair;
- importorg.apache.http.client.HttpClient;
- importorg.apache.http.client.entity.UrlEncodedFormEntity;
- importorg.apache.http.client.methods.HttpPost;
- importorg.apache.http.impl.client.DefaultHttpClient;
- importorg.apache.http.message.BasicNameValuePair;
- importorg.json.JSONException;
- importorg.json.JSONObject;
- publicclassBaseProtocol{
- privateStringBuildersb=newStringBuilder();
- privateHttpClienthttpClient;
- privateHttpPosthttpRequest;
- privateHttpResponseresponse;
- privateList
nameValuePair=newArrayList (); - BaseProtocol(){
- httpClient=newDefaultHttpClient();
- }
- /**
- *向服务器端发送请求
- *
- *@paramurl
- *@throw***ception
- */
- protectedvoidpack(Stringurl)throw***ception{
- httpClient=newDefaultHttpClient();
- httpRequest=newHttpPost(url);
- httpRequest.setEntity(newUrlEncodedFormEntity(nameValuePair));
- response=httpClient.execute(httpRequest);
- }
- /**
- *得到返回数据
- *
- *@paramurl
- *@return
- *@throw***ception
- */
- protectedvoidparse()throw***ception{
- //TODO状态处理500200
- if(response.getStatusLine().getStatusCode()==200){
- BufferedReaderbufferedReader2=newBufferedReader(
- newInputStreamReader(response.getEntity().getContent()));
- for(Strings=bufferedReader2.readLine();s!=null;s=bufferedReader2
- .readLine()){
- sb.append(s);
- }
- }
- }
- /**
- *向服务器发送信息
- *
- *@paramkey
- *@paramvalue
- */
- publicvoidaddNameValuePair(Stringkey,Stringvalue){
- nameValuePair.add(newBasicNameValuePair(key,value));
- }
- /**
- *返回JSONObject对象数据模型
- *
- *@return
- *@throwsJSONException
- */
- publicJSONObjectgetJSON()throwsJSONException{
- returnnewJSONObject(sb.toString());
- }
- }
接着是登陆协议,在这里我只是模拟登陆使用的一个类,仅供大家参考:
- packagecom.jclick.protocol;
- importorg.json.JSONObject;
- importcom.jclick.bean.User;
- publicclassLoginProtocolextendsBaseProtocol{
- privatefinalstaticStringURL="";
- publicbooleancheckLogin(Userusr){
- try{
- pack(URL);
- parse();
- JSONObjectobj=this.getJSON();
- if(obj.getString("result").equals("failed")){
- returnfalse;
- }else{
- returntrue;
- }
- }catch(Exceptione){
- e.printStackTrace();
- returnfalse;
- }
- }
- }
- packagecom.jclick.protocol;
- importorg.json.JSONObject;
- importcom.jclick.bean.User;
- publicclassLoginProtocolextendsBaseProtocol{
- privatefinalstaticStringURL="";
- publicbooleancheckLogin(Userusr){
- try{
- pack(URL);
- parse();
- JSONObjectobj=this.getJSON();
- if(obj.getString("result").equals("failed")){
- returnfalse;
- }else{
- returntrue;
- }
- }catch(Exceptione){
- e.printStackTrace();
- returnfalse;
- }
- }
- }
然后是User实体类,主要用于保存用户信息:
- packagecom.jclick.bean;
- publicclassUser{
- privateStringusername;
- privateStringpassword;
- publicStringgetUsername(){
- returnusername;
- }
- publicvoidsetUsername(Stringusername){
- this.username=username;
- }
- publicStringgetPassword(){
- returnpassword;
- }
- publicvoidsetPassword(Stringpassword){
- this.password=password;
- }
- }
- packagecom.jclick.bean;
- publicclassUser{
- privateStringusername;
- privateStringpassword;
- publicStringgetUsername(){
- returnusername;
- }
- publicvoidsetUsername(Stringusername){
- this.username=username;
- }
- publicStringgetPassword(){
- returnpassword;
- }
- publicvoidsetPassword(Stringpassword){
- this.password=password;
- }
- }
最后就是LoginActivity里边判断登陆的代码了,详细代码不再贴出来了,仅贴一个判断登陆的代码:
- privatevoidcheckedData(){
- username=((EditText)findViewById(R.id.username)).getText().toString();
- password=((EditText)findViewById(R.id.password)).getText().toString();
- Useruser=newUser();
- user.setUsername(username);
- user.setPassword(password);
- LoginProtocollogin=newLoginProtocol();
- booleanresult=login.checkLogin(user);
- if(result){SpiderCache.getInstance().setUserSession(user);
- Toast.makeText(getApplicationContext(),"登录成功",1000).show();
- Intentintent=newIntent();
- intent.setClass(LoginActivity.this,WelcomeActivity.class);
- startActivity(intent);
- }else{Toast.makeText(LoginActivity.this,"密码或用户名不匹配,请重新输入!",1000).show();
- }
- }
- privatevoidcheckedData(){
- username=((EditText)findViewById(R.id.username)).getText().toString();
- password=((EditText)findViewById(R.id.password)).getText().toString();
- Useruser=newUser();
- user.setUsername(username);
- user.setPassword(password);
- LoginProtocollogin=newLoginProtocol();
- booleanresult=login.checkLogin(user);
- if(result){ SpiderCache.getInstance().setUserSession(user);
- Toast.makeText(getApplicationContext(),"登录成功",1000).show();
- Intentintent=newIntent();
- intent.setClass(LoginActivity.this,WelcomeActivity.class);
- startActivity(intent);
- }else{ Toast.makeText(LoginActivity.this,"密码或用户名不匹配,请重新输入!",1000).show();
- }
- }
以上代码为了跟大家分享一下,感觉手机端和服务器双向开发非常过瘾。同时对Android的兴趣大大提升,它也没有我们想象中的那么难。