Android集合SSH搭建伺服器用戶端請求

來源:互聯網
上載者:User

 首先在伺服器端,星空採用的是SSH架構,struts2集合了json外掛程式,伺服器和用戶端的資訊互動採用的JSON來傳輸,由於在伺服器端用了Struts2,所以 星空 就用裝了一個JSON外掛程式,這樣,很輕易的就把伺服器端的資訊用JSON的形式發送到了手機端~~以下是代碼,歡迎eoe的朋友們拍磚~~

首先,在伺服器端搭建好SSH架構,具體細節就不在陳述~struts xml配置如下:

Java代碼:

  1. <package name="login" extends="json-default">  
  2.      <action name="login" class="com.jclick.test.LoginAction" method="login">  
  3.         <result type="json"><paramname="includeProperties">result</param></result>  
  4.      </action>  
  5. </package>  

複製代碼

手機端的代碼如下:

首先,手機端有一個緩衝類,主要用於緩衝一些手機端需要訪問的資料,這樣的好處是可以達達節省手機和伺服器的互動,用單例實現的:

Java代碼:

  1. package com.jclick.cache;  
  2.    
  3. import com.jclick.bean.User;  
  4.   
  5. public class Cache {  
  6.       
  7.      private User User;  
  8.       
  9.      private Cache(){  
  10.            
  11.      }  
  12.      /** 構造單例 */  
  13.      private static class CacheHolder{  
  14.          private static final Cache INSTANCE = new Cache();  
  15.      }  
  16.      public Cache getInstance(){  
  17.          return CacheHolder.INSTANCE;  
  18.      }  
  19.      public User getUser() {  
  20.          return User;  
  21.      }  
  22.      public void setUser(User User) {  
  23.          this.User = User;  
  24.      }  
  25.    
  26. }  

複製代碼

接著開始書寫手機端的協議,使用者向伺服器發送請求,同時伺服器反饋給手機端資訊的:

Java代碼:

  1. package com.jclick.protocol;  
  2.    
  3. import java.io.BufferedReader;  
  4. import java.io.InputStreamReader;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.    
  8. import org.apache.http.HttpResponse;  
  9. import org.apache.http.NameValuePair;  
  10. import org.apache.http.client.HttpClient;  
  11. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  12. import org.apache.http.client.methods.HttpPost;  
  13. import org.apache.http.impl.client.DefaultHttpClient;  
  14. import org.apache.http.message.BasicNameValuePair;  
  15. import org.json.JSONException;  
  16. import org.json.JSONObject;  
  17.    
  18. public class BaseProtocol {  
  19.      private StringBuilder sb = new StringBuilder();  
  20.    
  21.      private HttpClient httpClient;  
  22.      private HttpPost httpRequest;  
  23.      private HttpResponse response;  
  24.    
  25.      private List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();  
  26.    
  27.      BaseProtocol() {  
  28.          httpClient = new DefaultHttpClient();  
  29.      }  
  30.    
  31.      /**
  32.       * 向伺服器端發送請求
  33.       *  
  34.       * @param url
  35.       * @throws Exception
  36.       */  
  37.      protected void pack(String url) throws Exception {  
  38.          httpClient = new DefaultHttpClient();  
  39.          httpRequest = new HttpPost(url);  
  40.    
  41.          httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePair));  
  42.          response = httpClient.execute(httpRequest);  
  43.      }  
  44.    
  45.      /**
  46.       * 得到返回資料
  47.       *  
  48.       * @param url
  49.       * @return
  50.       * @throws Exception
  51.       */  
  52.      protected void parse() throws Exception {  
  53.          // TODO 狀態處理 500 200  
  54.          if (response.getStatusLine().getStatusCode() == 200) {  
  55.    
  56.              BufferedReader bufferedReader2 = new BufferedReader(  
  57.                      new InputStreamReader(response.getEntity().getContent()));  
  58.              for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2  
  59.                      .readLine()) {  
  60.                  sb.append(s);  
  61.              }  
  62.          }  
  63.      }  
  64.    
  65.      /**
  66.       * 向伺服器發送資訊
  67.       *  
  68.       * @param key
  69.       * @param value
  70.       */  
  71.      public void addNameValuePair(String key, String value) {  
  72.          nameValuePair.add(new BasicNameValuePair(key, value));  
  73.      }  
  74.    
  75.      /**
  76.       * 返回JSONObject對象資料模型
  77.       *  
  78.       * @return
  79.       * @throws JSONException
  80.       */  
  81.      public JSONObject getJSON() throws JSONException {  
  82.          return new JSONObject(sb.toString());  
  83.      }  
  84.    
  85. }  

複製代碼

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

Java代碼:

  1. package com.jclick.protocol;  
  2.    
  3. import org.json.JSONObject;  
  4.    
  5. import com.jclick.bean.User;  
  6.    
  7. public class LoginProtocol extends BaseProtocol{  
  8.       
  9.      private final static String URL = "http://localhost:8080/test/login";  
  10.       
  11.      public boolean checkLogin(User usr){  
  12.          try {  
  13.              pack(URL);  
  14.              parse();  
  15.              JSONObject obj = this.getJSON();  
  16.              if(obj.getString("result").equals("failed")){  
  17.                  return false;  
  18.              }else{  
  19.                  return true;  
  20.              }  
  21.          } catch (Exception e) {  
  22.              e.printStackTrace();  
  23.              return false;  
  24.          }  
  25.      }  
  26.    
  27. }  

複製代碼

然後是User實體類,主要用於儲存使用者資訊:

Java代碼:

  1. package com.jclick.bean;  
  2.    
  3. public class User {  
  4.      private String username;  
  5.      private String password;  
  6.      public String getUsername() {  
  7.          return username;  
  8.      }  
  9.      public void setUsername(String username) {  
  10.          this.username = username;  
  11.      }  
  12.      public String getPassword() {  
  13.          return password;  
  14.      }  
  15.      public void setPassword(String password) {  
  16.          this.password = password;  
  17.      }  
  18.    
  19. }  

複製代碼

最後就是LoginActivity裡邊判斷登陸的代碼了,僅貼一個判斷登陸的代碼:

Java代碼:

  1. private void checkedData(){  
  2.      username = ((EditText)findViewById(R.id.username)).getText().toString();  
  3.      password = ((EditText)findViewById(R.id.password)).getText().toString();  
  4.         
  5.      User user = new User();  
  6.      user.setUsername(username);  
  7.      user.setPassword(password);  
  8.      LoginProtocol login = new LoginProtocol();  
  9.      boolean result = login.checkLogin(user);  
  10.       
  11.      if(result){                 SpiderCache.getInstance().setUserSession(user);  
  12.          Toast.makeText(getApplicationContext(), "登入成功", 1000).show();  
  13.         Intent intent = new Intent ();  
  14.          intent.setClass(LoginActivity.this,WelcomeActivity.class);  
  15.          startActivity(intent);  
  16.      }else{              Toast.makeText(LoginActivity.this,"密碼或使用者名稱不匹配,請重新輸入!",1000).show();  
  17.      }  
  18. }  
      轉自: http://www.apkbus.com/android-14058-1-3.html 

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.