Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 高級開發 >> 用Android搭建客戶端 手機和服務器交互開發實例

用Android搭建客戶端 手機和服務器交互開發實例

編輯:高級開發

筆者以前是學的Java EE,由於項目需要要開發android,所以臨時補了一個多星期,主要是手機端和服務器端交互,雙向開發的。

首先在服務器端,我采用的是SSH框架,struts 2集合了JSON插件,服務器和客戶端的信息交互采用的JSON來傳輸,由於在服務器端用了Struts 2,所以我就用裝了一個JSON插件。這樣,很輕易的就把服務器端的信息用JSON的形式發送到了手機端。以下是代碼:

首先,在服務器端搭建好SSH框架,具體細節就不在陳述。struts.XML配置如下:

  1. <packagename="login"extends="JSon-default">
  2. <actionname="login"class="com.jclick.test.LoginAction"method="login">
  3. <resulttype="JSon"><paramname="includePropertIEs">result</param></result>
  4. </action>
  5. </package>
  6. <packagename="login"extends="JSon-default">
  7. <actionname="login"class="com.jclick.test.LoginAction"method="login">
  8. <resulttype="JSon"><paramname="includePropertIEs">result</param></result>
  9. </action>
  10. </package>

手機端的代碼如下:

首先,手機端有一個緩存類,主要用於緩存一些手機端需要訪問的數據,這樣的好處是可以達達節省手機和服務器的交互,用單例實現的:

  1. packagecom.jclick.cache;
  2. importcom.jclick.bean.User;
  3. publicclassCache{
  4. privateUserUser;
  5. privateCache(){
  6. }
  7. /**構造單例*/
  8. privatestaticclassCacheHolder{
  9. privatestaticfinalCacheINSTANCE=newCache();
  10. }
  11. publicCachegetInstance(){
  12. returnCacheHolder.INSTANCE;
  13. }
  14. publicUsergetUser(){
  15. returnUser;
  16. }
  17. publicvoidsetUser(UserUser){
  18. this.User=User;
  19. }
  20. }
  21. packagecom.jclick.cache;
  22. importcom.jclick.bean.User;
  23. publicclassCache{
  24. privateUserUser;
  25. privateCache(){
  26. }
  27. /**構造單例*/
  28. privatestaticclassCacheHolder{
  29. privatestaticfinalCacheINSTANCE=newCache();
  30. }
  31. publicCachegetInstance(){
  32. returnCacheHolder.INSTANCE;
  33. }
  34. publicUsergetUser(){
  35. returnUser;
  36. }
  37. publicvoidsetUser(UserUser){
  38. this.User=User;
  39. }
  40. }

接著開始書寫手機端的協議,用戶向服務器發送請求,同時服務器反饋給手機端信息的:

  1. packagecom.jclick.protocol;
  2. importJava.io.BufferedReader;
  3. importJava.io.InputStreamReader;
  4. importJava.util.ArrayList;
  5. importJava.util.List;
  6. importorg.apache.http.HttpResponse;
  7. importorg.apache.http.NameValuePair;
  8. importorg.apache.http.client.HttpClIEnt;
  9. importorg.apache.http.clIEnt.entity.UrlEncodedFormEntity;
  10. importorg.apache.http.clIEnt.methods.HttpPost;
  11. importorg.apache.http.impl.client.DefaultHttpClIEnt;
  12. importorg.apache.http.message.BasicNameValuePair;
  13. importorg.json.JSONException;
  14. importorg.json.JSONObject;
  15. publicclassBaseProtocol{
  16. privateStringBuildersb=newStringBuilder();
  17. privateHttpClienthttpClIEnt;
  18. privateHttpPosthttpRequest;
  19. privateHttpResponseresponse;
  20. privateList<NameValuePair>nameValuePair=newArrayList<NameValuePair>();
  21. BaseProtocol(){
  22. httpClient=newDefaultHttpClIEnt();
  23. }
  24. /**
  25. *向服務器端發送請求
  26. *
  27. *@paramurl
  28. *@throwsException
  29. */
  30. protectedvoidpack(Stringurl)throwsException{
  31. httpClient=newDefaultHttpClIEnt();
  32. httpRequest=newHttpPost(url);
  33. httpRequest.setEntity(newUrlEncodedFormEntity(nameValuePair));
  34. response=httpClIEnt.execute(httpRequest);
  35. }
  36. /**
  37. *得到返回數據
  38. *
  39. *@paramurl
  40. *@return
  41. *@throwsException
  42. */
  43. protectedvoidparse()throwsException{
  44. //TODO狀態處理500200
  45. if(response.getStatusLine().getStatusCode()==200){
  46. BufferedReaderbufferedReader2=newBufferedReader(
  47. newInputStreamReader(response.getEntity().getContent()));
  48. for(Strings=bufferedReader2.readLine();s!=null;s=bufferedReader2
  49. .readLine()){
  50. sb.append(s);
  51. }
  52. }
  53. }
  54. /**
  55. *向服務器發送信息
  56. *
  57. *@paramkey
  58. *@paramvalue
  59. */
  60. publicvoidaddNameValuePair(Stringkey,Stringvalue){
  61. nameValuePair.add(newBasicNameValuePair(key,value));
  62. }
  63. /**
  64. *返回JSONObject對象數據模型
  65. *
  66. *@return
  67. *@throwsJSONException
  68. */
  69. publicJSONObjectgetJSON()throwsJSONException{
  70. returnnewJSONObject(sb.toString());
  71. }
  72. }
  73. packagecom.jclick.protocol;
  74. importJava.io.BufferedReader;
  75. importJava.io.InputStreamReader;
  76. importJava.util.ArrayList;
  77. importJava.util.List;
  78. importorg.apache.http.HttpResponse;
  79. importorg.apache.http.NameValuePair;
  80. importorg.apache.http.client.HttpClIEnt;
  81. importorg.apache.http.clIEnt.entity.UrlEncodedFormEntity;
  82. importorg.apache.http.clIEnt.methods.HttpPost;
  83. importorg.apache.http.impl.client.DefaultHttpClIEnt;
  84. importorg.apache.http.message.BasicNameValuePair;
  85. importorg.json.JSONException;
  86. importorg.json.JSONObject;
  87. publicclassBaseProtocol{
  88. privateStringBuildersb=newStringBuilder();
  89. privateHttpClienthttpClIEnt;
  90. privateHttpPosthttpRequest;
  91. privateHttpResponseresponse;
  92. privateList<NameValuePair>nameValuePair=newArrayList<NameValuePair>();
  93. BaseProtocol(){
  94. httpClient=newDefaultHttpClIEnt();
  95. }
  96. /**
  97. *向服務器端發送請求
  98. *
  99. *@paramurl
  100. *@throwsException
  101. */
  102. protectedvoidpack(Stringurl)throwsException{
  103. httpClient=newDefaultHttpClIEnt();
  104. httpRequest=newHttpPost(url);
  105. httpRequest.setEntity(newUrlEncodedFormEntity(nameValuePair));
  106. response=httpClIEnt.execute(httpRequest);
  107. }
  108. /**
  109. *得到返回數據
  110. *
  111. *@paramurl
  112. *@return
  113. *@throwsException
  114. */
  115. protectedvoidparse()throwsException{
  116. //TODO狀態處理500200
  117. if(response.getStatusLine().getStatusCode()==200){
  118. BufferedReaderbufferedReader2=newBufferedReader(
  119. newInputStreamReader(response.getEntity().getContent()));
  120. for(Strings=bufferedReader2.readLine();s!=null;s=bufferedReader2
  121. .readLine()){
  122. sb.append(s);
  123. }
  124. }
  125. }
  126. /**
  127. *向服務器發送信息
  128. *
  129. *@paramkey
  130. *@paramvalue
  131. */
  132. publicvoidaddNameValuePair(Stringkey,Stringvalue){
  133. nameValuePair.add(newBasicNameValuePair(key,value));
  134. }
  135. /**
  136. *返回JSONObject對象數據模型
  137. *
  138. *@return
  139. *@throwsJSONException
  140. */
  141. publicJSONObjectgetJSON()throwsJSONException{
  142. returnnewJSONObject(sb.toString());
  143. }
  144. }

接著是登陸協議,在這裡我只是模擬登陸使用的一個類,僅供大家參考:

  1. packagecom.jclick.protocol;
  2. importorg.json.JSONObject;
  3. importcom.jclick.bean.User;
  4. publicclassLoginProtocolextendsBaseProtocol{
  5. privatefinalstaticStringURL="http://localhost:8080/test/login";
  6. publicbooleancheckLogin(Userusr){
  7. try{
  8. pack(URL);
  9. parse();
  10. JSONObjectobj=this.getJSON();
  11. if(obj.getString("result").equals("failed")){
  12. returnfalse;
  13. }else{
  14. returntrue;
  15. }
  16. }catch(Exceptione){
  17. e.printStackTrace();
  18. returnfalse;
  19. }
  20. }
  21. }
  22. packagecom.jclick.protocol;
  23. importorg.json.JSONObject;
  24. importcom.jclick.bean.User;
  25. publicclassLoginProtocolextendsBaseProtocol{
  26. privatefinalstaticStringURL="http://localhost:8080/test/login";
  27. publicbooleancheckLogin(Userusr){
  28. try{
  29. pack(URL);
  30. parse();
  31. JSONObjectobj=this.getJSON();
  32. if(obj.getString("result").equals("failed")){
  33. returnfalse;
  34. }else{
  35. returntrue;
  36. }
  37. }catch(Exceptione){
  38. e.printStackTrace();
  39. returnfalse;
  40. }
  41. }
  42. }

然後是User實體類,主要用於保存用戶信息:

  1. packagecom.jclick.bean;
  2. publicclassUser{
  3. privateStringusername;
  4. privateStringpassWord;
  5. publicStringgetUsername(){
  6. returnusername;
  7. }
  8. publicvoidsetUsername(Stringusername){
  9. this.username=username;
  10. }
  11. publicStringgetPassWord(){
  12. returnpassWord;
  13. }
  14. publicvoidsetPassword(StringpassWord){
  15. this.password=passWord;
  16. }
  17. }
  18. packagecom.jclick.bean;
  19. publicclassUser{
  20. privateStringusername;
  21. privateStringpassWord;
  22. publicStringgetUsername(){
  23. returnusername;
  24. }
  25. publicvoidsetUsername(Stringusername){
  26. this.username=username;
  27. }
  28. publicStringgetPassWord(){
  29. returnpassWord;
  30. }
  31. publicvoidsetPassword(StringpassWord){
  32. this.password=passWord;
  33. }
  34. }

最後就是LoginActivity裡邊判斷登陸的代碼了,詳細代碼不再貼出來了,僅貼一個判斷登陸的代碼:

  1. privatevoidcheckedData(){
  2. username=((EditText)findVIEwById(R.id.username)).getText().toString();
  3. password=((EditText)findVIEwById(R.id.passWord)).getText().toString();
  4. Useruser=newUser();
  5. user.setUsername(username);
  6. user.setPassword(passWord);
  7. LoginProtocollogin=newLoginProtocol();
  8. booleanresult=login.checkLogin(user);
  9. if(result){SpiderCache.getInstance().setUserSession(user);
  10. Toast.makeText(getApplicationContext(),"登錄成功",1000).show();
  11. Intentintent=newIntent();
  12. intent.setClass(LoginActivity.this,WelcomeActivity.class);
  13. startActivity(intent);
  14. }else{Toast.makeText(LoginActivity.this,"密碼或用戶名不匹配,請重新輸入!",1000).show();
  15. }
  16. }
  17. privatevoidcheckedData(){
  18. username=((EditText)findVIEwById(R.id.username)).getText().toString();
  19. password=((EditText)findVIEwById(R.id.passWord)).getText().toString();
  20. Useruser=newUser();
  21. user.setUsername(username);
  22. user.setPassword(passWord);
  23. LoginProtocollogin=newLoginProtocol();
  24. booleanresult=login.checkLogin(user);
  25. if(result){ SpiderCache.getInstance().setUserSession(user);
  26. Toast.makeText(getApplicationContext(),"登錄成功",1000).show();
  27. Intentintent=newIntent();
  28. intent.setClass(LoginActivity.this,WelcomeActivity.class);
  29. startActivity(intent);
  30. }else{ Toast.makeText(LoginActivity.this,"密碼或用戶名不匹配,請重新輸入!",1000).show();
  31. }
  32. }

以上代碼為了跟大家分享一下,感覺手機端和服務器雙向開發非常過瘾。同時對android的興趣大大提升,它也沒有我們想象中的那麼難。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved