Android 網絡通訊架構學習

最近跟着雲課堂上的極客學院作安卓APP,學習了課程裏面介紹的一種網絡通訊架構。清晰明瞭,比我本身東一塊西一塊拼湊出來的要好不少。在這裏記錄一下。java

 

雲課堂的鏈接:http://study.163.com/course/courseMain.htm?courseId=917001android

 

目錄:json

1、Android端實現服務器

1.1 架構圖網絡

1.2 NetworkConnection.java實現架構

1.3 Logic.java實現app

1.4 Activity.java實現ide

2、測試函數

2.1 服務器配置學習

2.2 結果

 

==============================

正文

1.1 架構圖

NetworkConnection.java裏面實現的,就是網絡通訊的內容。他不負責任何邏輯處理,只提供網絡通訊,將邏輯處理過程經過回調函數的方式留給上層的Logic.java實現

Logic.java針對具體的處理事件,實現處理邏輯,如數據的處理,網絡通訊成功或失敗的後續處理等。與界面的交流等主要經過回調函數,留給Activity.java實現

Activity.java是界面類,主要獲取界面內容和更新界面,經過實現Logic.java 的回調函數進行頁面的更新。

以一個登錄的例子,其源代碼組織如圖:

 

1.2 NetworkConnection.java的實現

package com.example.networkarch.net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;



public class NetConnection {
    
    public NetConnection(final String url,
            final HttpMethod method,
            final SuccessCallback successCallback,
            final FailCallback failCallback,
            final String ... kvs){
        
        System.out.println("4");
        
        
        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... arg0) {

                StringBuffer paramsStr = new StringBuffer();
                for(int i  = 0; i < kvs.length; i += 2){
                    paramsStr.append(kvs[i]).append("+").append(kvs[i+1]).append("&");
                }
                
                
                
                URLConnection uc;
                
                try {
                    
                    
                    switch (method) {
                    case POST:
                        
                        uc = new URL(url).openConnection();
                        uc.setDoOutput(true);
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(uc.getOutputStream()));
                        bw.write(paramsStr.toString());
                        bw.flush();
                        
                        break;

                    default:
                        
                        uc = new URL(url + "?" + paramsStr.toString()).openConnection();
                        break;
                    }
                    
                    
                    BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                    String line = null;
                    
                    StringBuffer result = new StringBuffer();
                    while((line = br.readLine()) != null){
                        result.append(line);
                    }
                    
                    System.out.println("++result: "+result.toString());
                    
                    
                    return result.toString();
                    
                    
                    
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
                
                return null;
            }
            
            protected void onPostExecute(String result){
                if(result != null){
                    if(successCallback != null){
                        successCallback.onSuccess(result);
                    }
                }
                else{
                    if(failCallback != null){
                        failCallback.onFail();
                    }
                }
                
                super.onPostExecute(result);
            }
            
        }.execute();
        
    }
    
    
    
    
    public static interface SuccessCallback{
        void onSuccess(String result);
    }
    
    public static interface FailCallback{
        void onFail();
    }

}

1.3 Logic.java的實現

package com.example.networkarch.logic;



import org.json.JSONException;
import org.json.JSONObject;

import com.example.networkarch.Config;
import com.example.networkarch.net.HttpMethod;
import com.example.networkarch.net.NetConnection;

public class Login {
    
    
    public Login(String username,
            String password,
            final SuccessCallback successCallback,
            final FailCallback failCallback){
        
        System.out.println("3");
        
        new NetConnection(Config.SERVER_URL, HttpMethod.POST,
                new NetConnection.SuccessCallback() {
                    
                    @Override
                    public void onSuccess(String result) {
                        if(successCallback != null){
                            
                            try {
                                System.out.println("result: "+result);
                                JSONObject jsonObject = new JSONObject(result);
                                
                                System.out.println("5");
                                
                                switch (jsonObject.getInt(Config.KEY_STATUS)) {
                                case Config.RESULT_STATUS_SUCCESS:
                                    
                                    if(successCallback != null){
                                        successCallback.onSuccess(jsonObject.getString(Config.VAULE_RESULT));
                                    }
                                    
                                    break;

                                default:
                                    if(failCallback != null){
                                        failCallback.onFail();
                                    }
                                    break;
                                }
                                
                                
                                
                            } catch (JSONException e) { 
                                
                                e.printStackTrace();
                                
                                if(failCallback != null){
                                    failCallback.onFail();
                                }
                            }
                            
                            
                        }
                        
                        
                        
                    }
                },
                new NetConnection.FailCallback() {
                    
                    @Override
                    public void onFail() {
                        if(failCallback != null){
                            failCallback.onFail();
                        }
                        
                    }
                }, "action", "login", "username", username, "password", password);
        
        
        
    }
    
    

    
    public static interface SuccessCallback{
        void onSuccess(String result);
    }
    
    public static interface FailCallback{
        void onFail();
    }
}

1.4 Activity.java的實現

package com.example.networkarch;

import com.example.networkarch.aty.ATYHome;
import com.example.networkarch.logic.Login;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends ActionBarActivity {
    
    private EditText username;
    private EditText password;
    private Button loginButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        username = (EditText)findViewById(R.id.et_username);
        password = (EditText)findViewById(R.id.et_password);
        loginButton = (Button)findViewById(R.id.bt_login);
        
        loginButton.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {

                //final ProgressDialog pd  = ProgressDialog.show(MainActivity.this, "Login...", "Please wait");
                
                System.out.println("2");
                
                new Login(username.getText().toString(), 
                        password.getText().toString(), 
                        new Login.SuccessCallback() {
                            
                            @Override
                            public void onSuccess(String result) {

                                Intent intent = new Intent(MainActivity.this, ATYHome.class);
                                intent.putExtra(Config.KEY_RESULT, result);
                                startActivity(intent);
                                
                                finish();
                                
                            }
                        }, 
                        new Login.FailCallback() {
                            
                            @Override
                            public void onFail() {
                                Toast.makeText(MainActivity.this, "Sorry", Toast.LENGTH_LONG).show();
                                
                            }
                        });
            }
        });

    }

    

}

另外補充兩個在代碼裏面用到的代碼:

package com.example.networkarch;

public class Config {
    
    
    public static final String SERVER_URL = "http://192.168.1.13:80/NetworkTest/test";
    public static final int RESULT_STATUS_SUCCESS = 2;
    public static final int RESULT_STATUS_FAIL = 1;
    
    
    
    public static final String KEY_STATUS = "status";
    public static final String KEY_RESULT = "result";
    
    
    
    public static final String VAULE_RESULT = "result";

}
package com.example.networkarch.net;

public enum HttpMethod {
    POST,GET
}

APP須要上網的權限,在Manifest.xml文件中補充以下代碼:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

 

 

 

 

2.1 Server端實現

package cn.example.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public class Result extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        doPost(request, response);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        System.out.println("++++++++++++++++get the infor");
        
        JSONObject json = new JSONObject();
        json.put("status", 2);
        json.put("result", "hello welcome");
        
        PrintWriter out = response.getWriter();
        out.write(json.toString());
    }

}

作一個簡單的servlet,只要收到請求了,就返回一個字符串「hello welcom」的json給APP

2.2 結果

APP將收到的結果提取出來,傳給下一個頁面並顯示出來便可。

相關文章
相關標籤/搜索