Anroid端通过HttpClient连接Web端

简介:从Web端取得List对象,传递到Android端并在activity中传递list对象

主要目的是验证登陆 从Web端取得List对象传递在Android端,并在Activity中以ListView的形式展示出来。

1.Android端通过HttpClient连接Web端

注:此处为验证登陆 在activity中

<span style="white-space:pre">	</span>/**
	 * 验证登陆
	 */
	private void doLoginHttpClienPost() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				String loginInfo = "";
				HttpClient httpClient = null;
				String url = "http://127.0.0.1:8080/ClassRoomManage/LoginServlet";//此处IP地址为Android端所连服务端的IP地址
				String username = et_username.getText().toString().trim();
				String password = et_password.getText().toString().trim();
				String type = "android";   //此处是为了在servlet中判断验证登陆是android端还是web端
				try {
					HttpPost post = new HttpPost(url);
					httpClient = new DefaultHttpClient();
					// 通过NameValuePair去存储数据
					ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
					list.add(new BasicNameValuePair("username", username));
					list.add(new BasicNameValuePair("password", password));
					list.add(new BasicNameValuePair("type", type));
					// 设置要发送的数据
					post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
					HttpResponse response = httpClient.execute(post);
					if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
						InputStream is = response.getEntity().getContent();
						Message message = new Message();
						if (is != null) {
							ObjectInputStream ois = new ObjectInputStream(is);
							message.what = LIST_RESPONSE;  //此处传递的信息会在下面讲到
							List<ClassroomBean> classroomBeanlist = new ArrayList<ClassroomBean>();
							classroomBeanlist = (List<ClassroomBean>) ois.readObject();
							Log.i("classroomBeanlist>", classroomBeanlist + "");
							System.out.println(classroomBeanlist);
							message.obj = classroomBeanlist;
							handler.sendMessage(message);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					httpClient.getConnectionManager().shutdown();
				}
			}
		}).start();
	}

2.Web端处理Android端的请求

注:此数是Web端servlet
<span style="white-space:pre">	</span>protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		PeopleBean peopleBean = new PeopleBean(); //此处代码为判断是否在数据库中存在此用户 也可以直接在DAO层处理 不必要实现过多接口
		peopleBean.setUsername(username);
		peopleBean.setPassword(password);
		PeopleBiz peopleBiz = new PeopleBizImpl();
		PeopleBean peopleBean2 = new PeopleBean();
		peopleBean2 = peopleBiz.login(peopleBean);
		if (username.equals(peopleBean2.getUsername())) {
			String type= request.getParameter("type");
			if(type.equals("android")){  //判断发送端  此处web端和android端跳转页面不同
				request.setAttribute("type", type);
				request.getRequestDispatcher("./FetchAllClassroomServlet").forward(request, response);
			}else{
				request.setAttribute("type", type);
				request.getRequestDispatcher("./FetchAllApplyinfoServlet").forward(request, response);
			}
		} else {
			System.out.println("fail");
			response.getOutputStream().write(("no").toString().getBytes());
		}
	}

3.序列化bean对象(Android和Web端的代码一样)

注:需要让bean对象实现Serializable接口
package com.classroom.bean; //注意 android端和web端的包名要保持一致 否则会报错

import java.io.Serializable;

public class ClassroomBean implements Serializable {
	/**
	 * 序列化对象
	 */
	private static final long serialVersionUID = 1L;
	private int id;
	private String classroomnumber;
	private String room;
	private int state;
	private String note;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getClassroomnumber() {
		return classroomnumber;
	}

	public void setClassroomnumber(String classroomnumber) {
		this.classroomnumber = classroomnumber;
	}

	public String getRoom() {
		return room;
	}

	public void setRoom(String room) {
		this.room = room;
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public String getNote() {
		return note;
	}

	public void setNote(String note) {
		this.note = note;
	}
}

4.通过Handler和Intent传递数据

注:此处和1.Android端通过HttpClient连接Web端 在同一个activity
<span style="white-space:pre">	</span>private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case SHOW_RESPONSE:
				String response = (String) msg.obj;
				if (response.equals("no")) {
					Toast.makeText(MainActivity.this, "对不起,账号或密码错误!",
							Toast.LENGTH_SHORT).show();
				}
			case LIST_RESPONSE:                                                                                                                   //通过message得到传过来的list对象 之后通过Intent android.content.Intent.putExtra(String name, Serializable value) 传递到下一个Activity中
				Object classroomBeanlist = msg.obj;
				Intent intent = new Intent(MainActivity.this,
						InfoActivity.class);
				intent.putExtra("list", (Serializable) classroomBeanlist);
				startActivity(intent);
			}
		}
	};

5.在传递到的Activity中处理list对象

public class InfoActivity extends Activity {
	private TextView username;
	private ListView lv;
	List<ClassroomBean> classroomBeanlist;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_classinfo);
		init();
		Intent intent = this.getIntent();
		classroomBeanlist = (List<ClassroomBean>) intent
				.getSerializableExtra("list");

		// 生成适配器的Item和动态数组对应的元素
		SimpleAdapter listItemAdapter = new SimpleAdapter(this, getData(),// 数据源
				R.layout.item_class,// ListItem的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "class_no", "class_name", "class_state",
						"class_note", "apply" }, new int[] { R.id.class_no,
						R.id.class_name, R.id.class_state, R.id.class_note,
						R.id.apply });
		// 添加并且显示
		lv.setAdapter(listItemAdapter);
	}

	private ArrayList<HashMap<String, Object>> getData() {
		// map.put(参数名字,参数值)
		ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
		for (ClassroomBean classroomBean : classroomBeanlist) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			String no = classroomBean.getClassroomnumber();
			map.put("class_no", no);
			String class_name = classroomBean.getRoom();
			map.put("class_name", class_name);
			String class_state = Integer.toString(classroomBean.getState());
			map.put("class_state", class_state);
			String class_note = classroomBean.getNote();
			map.put("class_note", class_note);
			listItem.add(map);
		}
		return listItem;
	}

	/**
	 * 初始化
	 */
	private void init() {
		username = (TextView) findViewById(R.id.username);
		lv = (ListView) findViewById(R.id.listView);
	}

之后就将传递来的数据显示在ListView当中了。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值