Android 网络通信架构学习
最近跟著云課堂上的極客學(xué)院做安卓APP,學(xué)習(xí)了課程里面介紹的一種網(wǎng)絡(luò)通信架構(gòu)。清晰明了,比我自己東一塊西一塊拼湊出來的要好很多。在這里記錄一下。
?
云課堂的連接:http://study.163.com/course/courseMain.htm?courseId=917001
?
目錄:
一、Android端實(shí)現(xiàn)
1.1 架構(gòu)圖
1.2 NetworkConnection.java實(shí)現(xiàn)
1.3 Logic.java實(shí)現(xiàn)
1.4 Activity.java實(shí)現(xiàn)
二、測試
2.1 服務(wù)器配置
2.2 結(jié)果
?
==============================
正文
1.1 架構(gòu)圖
NetworkConnection.java里面實(shí)現(xiàn)的,就是網(wǎng)絡(luò)通信的內(nèi)容。他不負(fù)責(zé)任何邏輯處理,只提供網(wǎng)絡(luò)通信,將邏輯處理過程通過回調(diào)函數(shù)的方式留給上層的Logic.java實(shí)現(xiàn)
Logic.java針對具體的處理事件,實(shí)現(xiàn)處理邏輯,如數(shù)據(jù)的處理,網(wǎng)絡(luò)通信成功或失敗的后續(xù)處理等。與界面的交流等主要通過回調(diào)函數(shù),留給Activity.java實(shí)現(xiàn)
Activity.java是界面類,主要獲取界面內(nèi)容和更新界面,通過實(shí)現(xiàn)Logic.java 的回調(diào)函數(shù)進(jìn)行頁面的更新。
以一個(gè)登陸的例子,其源代碼組織如圖:
?
1.2 NetworkConnection.java的實(shí)現(xiàn)
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>() {@Overrideprotected 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的實(shí)現(xiàn)
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() {@Overridepublic 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() {@Overridepublic 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的實(shí)現(xiàn)
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;@Overrideprotected 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() {@Overridepublic 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() {@Overridepublic void onSuccess(String result) {Intent intent = new Intent(MainActivity.this, ATYHome.class);intent.putExtra(Config.KEY_RESULT, result);startActivity(intent);finish();}}, new Login.FailCallback() {@Overridepublic void onFail() {Toast.makeText(MainActivity.this, "Sorry", Toast.LENGTH_LONG).show();}});}});}}另外補(bǔ)充兩個(gè)在代碼里面用到的代碼:
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需要上網(wǎng)的權(quán)限,在Manifest.xml文件中補(bǔ)充如下代碼:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>?
?
?
?
2.1 Server端實(shí)現(xiàn)
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());}}做一個(gè)簡單的servlet,只要收到請求了,就返回一個(gè)字符串“hello welcom”的json給APP
2.2 結(jié)果
APP將收到的結(jié)果提取出來,傳給下一個(gè)頁面并顯示出來即可。
轉(zhuǎn)載于:https://www.cnblogs.com/zhawj159753/p/4248138.html
總結(jié)
以上是生活随笔為你收集整理的Android 网络通信架构学习的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS 证书与签名 解惑详解
- 下一篇: session 学习