1.Android访问Web应用
这里我们写一个用手机访问web应用的demo,整体思路是:
1、通过手机访问web应用,并向服务器发送信息。
2、服务器接收客户端信息。
3、服务器处理数据(解析xml文件)。
4、重组信息,返回给客户端。
一、服务器代码
首先,建立一个web工程:Test1
然后新建一个servlet,用于手机客户端调用。
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.util.ArrayList;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.ServletInputStream;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.parsers.ParserConfigurationException;
- import org.w3c.dom.Document;
- import org.w3c.dom.Node;
- import org.w3c.dom.NodeList;
- import org.xml.sax.SAXException;
- public class ServletDemo extends HttpServlet {
- /**
- * Constructor of the object.
- */
- public ServletDemo() {
- super();
- }
- /**
- * Destruction of the servlet. <br>
- */
- public void destroy() {
- super.destroy();
- }
- /**
- * The doGet method of the servlet. <br>
- *
- * This method is called when a form has its tag value method equals to get.
- *
- * @param request the request send by the client to the server
- * @param response the response send by the server to the client
- * @throws ServletException if an error occurred
- * @throws IOException if an error occurred
- */
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html");
- this.doPost(request, response);
- }
- /**
- * The doPost method of the servlet. <br>
- *
- * This method is called when a form has its tag value method equals to post.
- *
- * @param request the request send by the client to the server
- * @param response the response send by the server to the client
- * @throws ServletException if an error occurred
- * @throws IOException if an error occurred
- */
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html");
- //获得客户端发送的数据
- ServletInputStream is = request.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(is));
- String requestString = reader.readLine();
- //向客户端返回数据
- String responseString = processStringRequest(requestString,request);
- ServletOutputStream os = response.getOutputStream();
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
- writer.write(responseString);
- //关闭资源
- writer.flush();
- writer.close();
- reader.close();
- os.close();
- }
- /**
- * Initialization of the servlet. <br>
- *
- * @throws ServletException if an error occure
- */
- public void init() throws ServletException {
- }
- private String processStringRequest(String requestString,HttpServletRequest request){
- List list = this.toRead(request.getRealPath("/")+"user.xml");
- String response = "";
- if(null != list && list.size() > 0){
- for(int i = 0 ; i < list.size(); i++){
- JavaBean a = (JavaBean)list.get(i);
- response += "client say:"+requestString+"server say: this is your info:"+a.getName()+"@"+a.getSex()+"@"+a.getAge();
- System.out.println(a.getName());
- }
- }else{
- response = "is wrong!";
- }
- return response;
- }
- public List toRead(String filename) {
- List alist = new ArrayList();
- try {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document document = db.parse(filename);
- NodeList employees = document.getChildNodes();
- for (int i = 0; i < employees.getLength(); i++) {
- Node employee = employees.item(i);
- NodeList employeeInfo = employee.getChildNodes();
- for (int j = 0; j < employeeInfo.getLength(); j++) {
- Node node = employeeInfo.item(j);
- NodeList employeeMeta = node.getChildNodes();
- JavaBean bean = new JavaBean();
- boolean status = false;
- for (int k = 0; k < employeeMeta.getLength(); k++) {
- if(employeeMeta.item(k).getNodeName().equals("name")){
- bean.setName(employeeMeta.item(k).getTextContent());
- }
- if(employeeMeta.item(k).getNodeName().equals("age")){
- bean.setAge(employeeMeta.item(k).getTextContent());
- }
- if(employeeMeta.item(k).getNodeName().equals("sex")){
- bean.setSex(employeeMeta.item(k).getTextContent());
- }
- status = true;
- }
- if(status){
- alist.add(bean);
- }
- }
- }
- } catch (FileNotFoundException e) {
- System.out.println(e.getMessage());
- } catch (ParserConfigurationException e) {
- System.out.println(e.getMessage());
- } catch (SAXException e) {
- System.out.println(e.getMessage());
- } catch (IOException e) {
- System.out.println(e.getMessage());
- }
- return alist;
- }
- }
web工程的web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4"
- xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
- http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <servlet>
- <description>This is the description of my J2EE component</description>
- <display-name>This is the display name of my J2EE component</display-name>
- <servlet-name>ServletDemo</servlet-name>
- <servlet-class>ServletDemo</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>ServletDemo</servlet-name>
- <url-pattern>/servlet/ServletDemo</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
xml文件格式
- <?xml version="1.0" encoding="GB2312" standalone="no"?>
- <employees>
- <employee>
- <name>user0</name>
- <sex>m</sex>
- <age>30</age>
- </employee>
- </employees>
解析xml文件用到的javabean:
- public class JavaBean {
- private String name;
- private String sex;
- private String age;
- public String getAge() {
- return age;
- }
- public void setAge(String age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getSex() {
- return sex;
- }
- public void setSex(String sex) {
- this.sex = sex;
- }
- }
这样 服务器端的工作就准备好了,启动、等待客户端连接。
二,客户端代码
1、新建Android工程
2、修改main。xml文件
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <EditText
- android:layout_height="wrap_content"
- android:id="@+id/address"
- android:layout_width="fill_parent"
- android:text="http://192.168.1.111:8089/Test1/servlet/ServletDemo"
- >
- </EditText>
- <Button
- android:id="@+id/ButtonGo"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="go!"
- >
- </Button>
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="#ffffff"
- android:textColor="#000000"
- android:id="@+id/pagetext"
- />
- </LinearLayout>
3、添加关键代码
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.Button;
- import android.widget.TextView;
- import android.util.Log;
- import android.view.View;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.URL;
- import java.net.URLConnection;
- public class ClientDemo extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- final TextView tView = (TextView) findViewById(R.id.pagetext);
- final Button button = (Button) findViewById(R.id.ButtonGo);
- button.setOnClickListener(new Button.OnClickListener() {
- public void onClick(View v) {
- String response_string = "";
- boolean out = true;
- boolean in = true;
- try {
- System.out.println("ty"+tView.getText().toString());
- URL url = new URL("http://192.168.1.111:8089/Test1/servlet/ServletDemo");
- URLConnection connection = url.openConnection();
- connection.setDoInput(in);
- connection.setDoOutput(out);
- BufferedWriter writer = null;
- //向服务器发送数据
- if(out){
- writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
- writer.write("I am clent request!!");
- writer.flush();
- }
- //接受服务器返回的数据
- BufferedReader reader = null;
- if(in){
- reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- response_string = reader.readLine();
- System.out.println("response: "+response_string);
- Log.v("test", response_string);
- tView.setText(response_string);
- }
- if(writer != null){
- writer.close();
- }
- if(reader != null){
- reader.close();
- }
- } catch (Exception e) {
- // TODO: handle exception
- System.out.println(e.getMessage());
- }
- }
- });
- }
- }
这样,整个demo就完成了
运行结果如下
1、程序启动
2、发送请求后
2.Android--模拟登陆用户名密码,使用File或openFileOutput保存文件
一、File:xml布局文件
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context=".MainActivity" >
- <TextView
- android:id="@+id/textView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:text="请输入用户名" />
- <EditText
- android:id="@+id/et_username"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignLeft="@+id/textView1"
- android:layout_below="@+id/textView1"
- android:ems="10"/>
- <TextView
- android:id="@+id/textView2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignLeft="@+id/et_username"
- android:layout_below="@+id/et_username"
- android:layout_marginTop="20dp"
- android:text="请输入用户密码" />
- <EditText
- android:id="@+id/ed_password"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignLeft="@+id/textView2"
- android:layout_below="@+id/textView2"
- android:ems="10"
- android:inputType="textPassword" >
- <requestFocus />
- </EditText>
- <CheckBox
- android:id="@+id/checkbox_remeber"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignTop="@+id/btn_login"
- android:text="记住我" />
- <Button
- android:id="@+id/btn_login"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignRight="@+id/et_username"
- android:layout_below="@+id/ed_password"
- android:layout_marginTop="27dp"
- android:gravity="left"
- android:onClick="login"
- android:text="登陆" />
- </RelativeLayout>
二、
File: MainActivity.java
- package com.jiangge.login;
- import java.util.Map;
- import android.app.Activity;
- import android.os.Bundle;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.View;
- import android.widget.CheckBox;
- import android.widget.EditText;
- import android.widget.Toast;
- import com.jiangge.login.service.LoginService;
- import com.jiangge.logindemo.R;
- public class MainActivity extends Activity {
- private static final String TAG = "MainActivity";
- private EditText mUsername;
- private EditText mPassword;
- private CheckBox mRemember;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- mUsername = (EditText) findViewById(R.id.et_username);
- mPassword = (EditText) findViewById(R.id.ed_password);
- mRemember = (CheckBox) findViewById(R.id.checkbox_remeber);
- Map<String, String> map = LoginService.getSavedUserInfo(this);
- if (map != null) {
- mUsername.setText(map.get("username"));
- mPassword.setText(map.get("password"));
- }
- }
- public void login(View view) {
- String username = mUsername.getText().toString().trim();
- String password = mPassword.getText().toString().trim();
- if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
- Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_LONG).show();
- }
- if (mRemember.isChecked()) {
- //保存用户名和密码
- Log.i(TAG, "保存用户名和密码");
- boolean result = LoginService.saveUserInfo(this, username, password);
- if (result) {
- Toast.makeText(this, "保存用户名和密码成功", Toast.LENGTH_LONG).show();
- }
- }
- //登录发送到服务器,服务器验证是否正确。模拟。
- if ("jiangge".equals(username) && "123".equals(password)) {
- Toast.makeText(this, "登录成功", Toast.LENGTH_LONG).show();
- }
- }
- }
File: LoginService.java
- package com.jiangge.login.service;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.HashMap;
- import java.util.Map;
- import android.content.Context;
- public class LoginService {
- //存数据
- public static boolean saveUserInfo(Context context, String username, String password){
- try {
- File file = new File(context.getFilesDir(), "info.txt"); //Do not hardcode "/data/"; use Context.getFilesDir().getPath() instead
- System.out.println("====>>>"+ context.getFilesDir());// /data/data/com.jiangge.logindemo/files
- FileOutputStream fos = new FileOutputStream(file);
- fos.write((username + "##" + password).getBytes());
- fos.close();
- return true;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- return false;
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
- }
- //取数据
- public static Map<String,String> getSavedUserInfo(Context context){
- try {
- File file = new File(context.getFilesDir(), "info.txt");
- FileInputStream fis = new FileInputStream(file);
- BufferedReader br = new BufferedReader(new InputStreamReader(fis));
- String str = br.readLine();
- br.close();
- String [] infos = str.split("##"); //jiangge##123
- Map<String,String> map = new HashMap<String, String>();
- map.put("username", infos[0]);
- map.put("password", infos[1]);
- return map;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- }
注:
保存文件:
- File file = new File(context.getFilesDir(), "info.txt"); //Do not hardcode "/data/"; use Context.getFilesDir().getPath() instead
- System.out.println("====>>>"+ context.getFilesDir());// /data/data/com.jiangge.logindemo/files
- FileOutputStream fos = new FileOutputStream(file);
- fos.write((username + "##" + password).getBytes());
- fos.close();
也可以将以上的核心代码,使用Activity提供的方法 openFileOutput(String name, int mode)
- FileOutputStream fos = context.openFileOutput("private.txt", Context.MODE_PRIVATE);
- fos.write((username + "##" + password).getBytes());
- fos.close();
保存到了 /data/data/包名/files/目录下
3.Android之记住登录名和密码 --- 使用Preference
简述:
在登陆的时候,有时候会遇到一个勾选框,用来询问是否保留用户名和密码
知识点:
SharedPreferences
用来访问程序的文件,从里面读出用户名和密码
代码实现:
MyPreference.java
- package com.aimp.help;
- import android.content.Context;
- import android.content.SharedPreferences;
- import android.content.SharedPreferences.Editor;
- /**
- *
- * 记录用户名,密码之类的首选项
- *
- */
- public class MyPreference {
- private static MyPreference preference = null;
- private SharedPreferences sharedPreference;
- private String packageName = "";
- private static final String LOGIN_NAME = "loginName"; //登录名
- private static final String PASSWORD = "password"; //密码
- private static final String IS_SAVE_PWD = "isSavePwd"; //是否保留密码
- public static synchronized MyPreference getInstance(Context context){
- if(preference == null)
- preference = new MyPreference(context);
- return preference;
- }
- public MyPreference(Context context){
- packageName = context.getPackageName() + "_preferences";
- sharedPreference = context.getSharedPreferences(
- packageName, context.MODE_PRIVATE);
- }
- public String getLoginName(){
- String loginName = sharedPreference.getString(LOGIN_NAME, "");
- return loginName;
- }
- public void SetLoginName(String loginName){
- Editor editor = sharedPreference.edit();
- editor.putString(LOGIN_NAME, loginName);
- editor.commit();
- }
- public String getPassword(){
- String password = sharedPreference.getString(PASSWORD, "");
- return password;
- }
- public void SetPassword(String password){
- Editor editor = sharedPreference.edit();
- editor.putString(PASSWORD, password);
- editor.commit();
- }
- public boolean IsSavePwd(){
- Boolean isSavePwd = sharedPreference.getBoolean(IS_SAVE_PWD, false);
- return isSavePwd;
- }
- public void SetIsSavePwd(Boolean isSave){
- Editor edit = sharedPreference.edit();
- edit.putBoolean(IS_SAVE_PWD, isSave);
- edit.commit();
- }
- }
LoginActivity.java
- package com.aimp.ui;
- import android.app.Activity;
- import android.content.Context;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.CheckBox;
- import android.widget.EditText;
- import com.aimp.R;
- import com.aimp.help.MyPreference;
- public class LoginActivity extends Activity implements OnClickListener {
- public final static String TAG = "LogingActivity";
- private EditText et_loginName, et_password;
- private Button bt_login;
- private CheckBox chk_keep_pwd;
- private Context mContext;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- mContext = this;
- setContentViewID(R.layout.activity_login);
- }
- public void setContentViewID(int viewId) {
- setContentView(viewId);
- initView();
- }
- public void initView() {
- et_loginName = (EditText) findViewById(R.id.username);
- et_password = (EditText) findViewById(R.id.password);
- bt_login = (Button) findViewById(R.id.login);
- bt_login.setOnClickListener(this);
- chk_keep_pwd = (CheckBox) findViewById(R.id.store_pwd);
- chk_keep_pwd.setChecked(
- MyPreference.getInstance(mContext).IsSavePwd());
- }
- @Override
- protected void onResume() {
- super.onResume();
- mContext = this;
- chk_keep_pwd.setChecked(MyPreference.getInstance(mContext).IsSavePwd());
- if (chk_keep_pwd.isChecked()) {
- et_loginName.setText(MyPreference.getInstance(mContext)
- .getLoginName());
- et_password
- .setText(MyPreference.getInstance(mContext).getPassword());
- }
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()){
- //登陆的时候,根据是否保留登陆名保留登录名,密码
- case R.id.login:
- if(chk_keep_pwd.isChecked()){
- MyPreference.getInstance(mContext)
- .SetLoginName(et_loginName.getText().toString().trim());
- MyPreference.getInstance(mContext)
- .SetPassword(et_password.getText().toString().trim());
- MyPreference.getInstance(mContext)
- .SetIsSavePwd(chk_keep_pwd.isChecked());
- }else{
- MyPreference.getInstance(mContext)
- .SetLoginName("");
- MyPreference.getInstance(mContext)
- .SetPassword("");
- MyPreference.getInstance(mContext)
- .SetIsSavePwd(chk_keep_pwd.isChecked());
- }
- Intent intent = new Intent(LoginActivity.this, SecondActivity.class);
- startActivity(intent);
- break;
- case R.id.store_pwd:
- chk_keep_pwd.setChecked(!chk_keep_pwd.isChecked());
- break;
- }
- }
- }
4.Android自定义框架之网络请求
框架起始篇...意义重大,影响深远....
适用场景,为了便于秒速我们定义网络请求的对象为Action,UI层调起Action发起网络请求,Action处理请求响应的结果,并通知UI层令其得到Action处理后的数据。
1、定义网络请求监听
- public interface HttpListener {
- /**
- * 完成网络请求
- * @param response
- */
- public void onComplete(String response);
- /**
- * 网络请求失败
- */
- public void onError();
- }
2、定义HTTP工具
主要用到request方法
- /**
- * HTTP工具类
- * @author: linxcool.hu
- */
- public class HttpUtil {
- private Context context;
- /**HTTP常量-GET请求*/
- public static final int HTTP_METHOD_GET=1;
- /**HTTP常量-POST请求*/
- public static final int HTTP_METHOD_POST=2;
- /**HTTP常量-请求限制时间*/
- public static final int HTTP_REQ_LIMIT_TIME=15*1000;
- /**HTTP常量-响应限制时间*/
- public static final int HTTP_RES_LIMIT_TIME=25*1000;
- //返回码
- public static final int RES_CODE_SUCCESS=200;
- public static final int RES_CODE_ERROR=1;
- public static final int RES_CODE_FAIL=2;
- private HttpClient client;
- private HttpResponse response;
- public HttpUtil(Context context) {
- this.context=context;
- }
- public HttpClient createHttpClient(){
- HttpParams params = new BasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(params, HTTP_REQ_LIMIT_TIME);
- HttpConnectionParams.setSoTimeout(params,HTTP_RES_LIMIT_TIME);
- HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
- HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
- return new DefaultHttpClient(params);
- }
- public HttpUriRequest createHttpRequest(String url,int method){
- HttpUriRequest request=null;
- if(method == HTTP_METHOD_GET){
- request=new HttpGet(url);
- }else{
- request=new HttpPost(url);
- }
- //关闭 100-Continue 询问
- request.getParams().setBooleanParameter(
- CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
- return request;
- }
- public boolean openUrl(HttpUriRequest request){
- client=createHttpClient();
- try {
- response=client.execute(request);
- return true;
- } catch (IOException e) {
- e.printStackTrace();
- response=null;
- }
- return false;
- }
- public String getHttpResponse(){
- String result = null;
- try {
- if(response==null)return null;
- HttpEntity entity = response.getEntity();
- InputStream inputStream = entity.getContent();
- ByteArrayOutputStream content = new ByteArrayOutputStream();
- int readBytes = 0;
- byte[] sBuffer = new byte[512];
- while ((readBytes = inputStream.read(sBuffer)) != -1)
- content.write(sBuffer, 0, readBytes);
- result = new String(content.toByteArray());
- result=URLDecoder.decode(result, "UTF-8");
- try {
- inputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }finally{
- if(client!=null)
- client.getConnectionManager().shutdown();
- }
- return result;
- }
- public void request(
- final String url,final HttpUriRequest request,final HttpListener listerner) {
- new Thread() {
- @Override
- public void run() {
- boolean ret = openUrl(request);
- if(!ret){
- listerner.onError();
- return;
- }
- listerner.onComplete(getHttpResponse());
- }
- }.start();
- }
- }
3、定义网络请求动作Action
每个网络请求动作都继承以下类
- /**
- * 基础动作类
- * @author: linxcool.hu
- */
- public abstract class BaseAction extends Observable implements HttpListener,Runnable{
- private static final String TAG="BaseAction";
- //动作ID列表 根据实际情况更改
- public static final int ACTION_ID_INTRO=1;
- public static final int ACTION_ID_SHARE=2;
- //响应状态结果
- public static final int SUCCESS=0;
- public static final int ERROR=1;
- public static final int EXCEPTION=2;
- //上下文对象
- protected Context context;
- protected ActionService actionService;
- //动作信息列表
- protected int actionId;
- protected HttpUtil httpUtil;
- protected int method;
- protected String content;
- //响应信息
- protected String response;
- protected String resMsg;
- public String getResMsg() {
- return resMsg;
- }
- public BaseAction(ActionService actionService,int actionId){
- this.actionService=actionService;
- this.context=actionService.getActivity();
- this.actionId=actionId;
- httpUtil=new HttpUtil(context);
- method=HttpUtil.HTTP_METHOD_POST;
- }
- /**
- * 执行网络请求动作
- */
- public void actionStart(){
- try {
- doRequest(
- httpUtil.REQUEST_HOST+getURL(),
- content);
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }
- protected void putBasicData(JSONObject jsonObj) throws JSONException{
- }
- public abstract void putData(Object... datas);
- public void doRequest(String url,String content) throws UnsupportedEncodingException{
- HttpUriRequest request=httpUtil.createHttpRequest(url, method);
- if(content != null){
- HttpPost post=(HttpPost) request;
- post.setEntity(new StringEntity(content));
- }
- httpUtil.request(url, request, this);
- }
- @Override
- public void onComplete(String response) {
- this.response=response;
- ((Activity)context).runOnUiThread(this);
- }
- @Override
- public void onError() {
- response=null;
- ((Activity)context).runOnUiThread(this);
- }
- private String getURL(){
- switch (actionId) {
- case ACTION_ID_INTRO:
- return "login";
- }
- }
- @Override
- public void run() {
- setChanged();
- if(response==null){
- notifyObservers(ERROR);
- return;
- }
- try {
- JSONObject obj = new JSONObject(response);
- int code=obj.getInt("code");
- if(code==HttpUtil.RES_CODE_SUCCESS){
- onResSuccess(obj);
- notifyObservers(SUCCESS);
- }else{
- resMsg=obj.getString("msg");
- notifyObservers(EXCEPTION);
- }
- } catch (Exception e) {
- e.printStackTrace();
- resMsg="数据解析错误";
- notifyObservers(ERROR);
- }
- }
- /**
- * 网络请求成功后将执行该方法
- * @param obj
- * @throws Exception
- */
- public abstract void onResSuccess(JSONObject obj) throws Exception;
- }
4、动作服务类根据ActionId获取对应Action
- /**
- * 动作服务对象
- * @author: linxcool.hu
- */
- public class ActionService {
- private Activity activity;
- public ActionService(Activity activity){
- this.activity=activity;
- }
- /**
- * 根据动作ID获取动作对象
- * @param actionId
- * @return
- */
- public BaseAction getAction(int actionId){
- switch (actionId) {
- case BaseAction.ACTION_ID_INTRO:
- return new IntroAction(this);
- case BaseAction.ACTION_ID_SHARE:
- return new ShareAction(this);
- }
- return null;
- }
- /**
- * 获取Context对象
- * @return
- */
- public Activity getActivity() {
- return activity;
- }
- }
5、在UI视图上实现Observer接口,并将该视图添加到对应的Action观察者队列中,在Update方法中处理界面逻辑
- @Override
- public void update(Observable observable, Object data) {
- int code=(Integer) data;
- switch (code) {
- case BaseAction.SUCCESS:
- break;
- case BaseAction.EXCEPTION:
- break;
- case BaseAction.ERROR:
- break;
- }
- }
本文详细介绍了如何使用手机访问web应用,包括建立web工程、创建servlet、处理客户端信息和服务器响应等关键步骤。
2601

被折叠的 条评论
为什么被折叠?



