最近跟着云课堂上的极客学院做安卓APP,学习了课程里面介绍的一种网络通信架构。清晰明了,比我自己东一块西一块拼凑出来的要好很多。在这里记录一下。
云课堂的连接:http://study.163.com/course/courseMain.htm?courseId=917001
目录:
一、Android端实现
1.1 架构图
1.2 NetworkConnection.java实现
1.3 Logic.java实现
1.4 Activity.java实现
二、测试
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将收到的结果提取出来,传给下一个页面并显示出来即可。
时间: 2024-11-03 03:30:58