`
gintama
  • 浏览: 52271 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

handler的使用、服务端客户端交互、Json、Gson

 
阅读更多
附件有完整代码

登录界面:


登录的Activity:
package com.example.knowledgedemo;

import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.entity.loginPerson;
import com.example.utils.HttpUtil;
import com.example.utils.ToastUtil;
import com.google.gson.Gson;

/**
 * 知识点:handler的使用、服务端客户端交互、Json、Gson、
 * @author somebody
 * 
 */
public class LoginDemo extends Activity {

	private EditText loginname, password;
	private Button login;
	private ProgressDialog progressdialog;
	private String name, pwd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		loginname = (EditText) findViewById(R.id.loginname);
		password = (EditText) findViewById(R.id.password);
		login = (Button) findViewById(R.id.login);
		login.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				login();//点击登录按钮
			}
		});
	}

	private void login() {
		showProgressDialog();//显示进度框
		new Thread() {
			public void run() {
				requestServer();//请求服务器
			}
		}.start();
	}

	private void showProgressDialog() {
		if (progressdialog == null) {
			progressdialog = new ProgressDialog(this);
		}
		if (progressdialog.isShowing()) {
			progressdialog.dismiss();
		}
		progressdialog.setTitle("提示");
		progressdialog.setMessage("正在登陆..");
		progressdialog.show();
	}
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			progressdialog.dismiss();
			switch (msg.what) {
			case 0:
				ToastUtil.longToast(getApplicationContext(),
						R.string.network_ok);//Toast 提示信息、登录成功
				break;
			case 1:
				ToastUtil.longToast(getApplicationContext(),
						R.string.network_not_ok);//登录失败
				break;
			case 2:
				ToastUtil.longToast(getApplicationContext(),
						R.string.network_not_ok);//TimeOut 网络连接失败
				break;
			default:
				break;
			}
		}
	};

	private void requestServer(){
		name = loginname.getText().toString();
		pwd = password.getText().toString();//获取用户名密码
		loginPerson person = new loginPerson();
		person.setLoginName(name);
		person.setPassWord(pwd);
		Gson g = new Gson();
		/*
		 * Gson将person对象转换为Json格式的字符串
		 * 此时obj = {"loginName":"1","passWord":"1"}
		 * */
		String obj = g.toJson(person);
		String result = HttpUtil.httpPostCodeParams("login",obj);//请求服务端、获取返回值
		JSONObject resultObject;
		if(result.startsWith("TimeOut")||result.length()==0){
			handler.sendEmptyMessage(2);//请求服务端超时
		}else{
			try {
				//如果不超时、返回的数据格式  {"result":"0"}
				resultObject = new JSONObject(result);
				result = resultObject.getString("result");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			if(result.equals("0")){
				handler.sendEmptyMessage(0);//登录成功
			}else if(result.equals("1")){
				handler.sendEmptyMessage(1);//登录失败
			}
		}
		
	}
	
}


存放用户名密码的LoginPerson对象:
package com.example.entity;

public class LoginPerson {

	private String loginName;

	private String passWord;

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getPassWord() {
		return passWord;
	}

	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}

}

请求服务端的方法:
package com.example.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

public class HttpUtil {

	/**
	 * 传递命令和参数
	 * 
	 * @param postCode
	 * @param obj
	 * @return
	 */
	public static String httpPostCodeParams(String postCode, String obj) {
		StringBuilder sbResponse = new StringBuilder();
		URL url;
		try {
			//请求的url = http://10.33.1.204:8888/KnowledgeManagementServer/Servlet/ 加  postCode
			//服务端ip、端口、服务端项目名、服务端使用servlet+命令的方式响应请求
			url = new URL(getUrl(postCode));
			
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setReadTimeout(Constants.connectTimeout);
			conn.setConnectTimeout(Constants.connectTimeout);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			DataOutputStream outStream = new DataOutputStream(
					conn.getOutputStream());
			outStream.writeUTF(obj.toString());
			outStream.flush();
			outStream.close();

			int cah = conn.getResponseCode();
			if (cah != 200) {
				return "TimeOut";
			}
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "utf-8")); 
			String lines;
			while ((lines = reader.readLine()) != null) {
				sbResponse.append(lines);
			}
			conn.disconnect();

		} catch (SocketTimeoutException e) {
			return "TimeOut";
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sbResponse.toString();
	}

	private static String getUrl(String postCode) {
		return Constants.server + postCode;
	}

}


Servlet相应类:
package com.ck.servlet;

import java.io.DataInputStream;
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 com.ck.entity.LoginPerson;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class LoginServlet extends HttpServlet{
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		PrintWriter out = resp.getWriter();

		DataInputStream dis = new DataInputStream(req.getInputStream());
		String param = dis.readUTF();
		Gson g = new Gson();
		LoginPerson person = g.fromJson(param, LoginPerson.class);
		JsonObject jsonObject = new JsonObject();
		if(person.getLoginName().equals("1")&&person.getPassWord().equals("1")){
			jsonObject.addProperty("result", "0");
		}else{
			jsonObject.addProperty("result", "1");
		}
		//{"result":"0"}
		out.print(jsonObject.toString());
		out.flush();
		out.close();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics