Android使用HTTP协议访问网络

功能概述:使用HttpURLConnection的GET方式实现登录,以及使用xUtil框架以GET和POST方式传递参数到后台实现登录功能

注:在使用xUtil框架前,需要导入包或者jar文件

1.后台部分

LoginServlet.java文件中

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name=request.getParameter("name");//用户名
		String pwd=request.getParameter("pwd");//密码
		String result="";//登录结果
		
		if ("sa".equals(name)&&"123".equals(pwd)) {
			result="ok";
		}else{
			result="false";
		}
		PrintWriter out=response.getWriter();
		out.write(result);
		out.flush();
		out.close();
	}

2.前端部分

2.1AndroidManifest.xml清单文件中开启网络权限

 <!-- 开启网络权限 -->
    <uses-permission android:name="android.permission.INTERNET"/>

2.2布局文件activity_main.xml中

 <!-- 用户名 -->
    <EditText
        android:id="@+id/etName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/ivPic"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:hint="请输入用户名" >

        <requestFocus />
    </EditText>

     <!-- 密码 -->
    <EditText
        android:id="@+id/etPwd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/etName"
        android:layout_alignRight="@+id/etName"
        android:layout_below="@+id/etName"
        android:ems="10"
        android:hint="请输入密码"
        android:inputType="textPassword" />

    <!-- 登录 -->
    <Button
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etPwd"
        android:layout_centerHorizontal="true"
        android:onClick="login"
        android:text="HttpURLConnection登录" />
    
     <!-- xUtil框架Get方式提交 -->
    <Button
        android:id="@+id/btnxUtilGet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_below="@+id/btnLogin"
        android:onClick="xGetLogin"
        android:text="xUtil框架Get方式提交" />
	
    <!-- xUtil框架Post方式提交 -->
    <Button
        android:id="@+id/btnxUtilPost"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnxUtilGet"
        android:layout_centerHorizontal="true"
        android:text="xUtil框架Post方式提交"
        android:onClick="xPostLogin" />

2.3MainActivity.java文件中

package com.t20.networkDemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
	protected static final int LOGIN_MSG = 0;
	private EditText etName;
	private EditText etPwd;

	/**
	 * 4.定义Handler,利用handleMessage()方法处理数据 类似于银行柜台的业务员,相应柜台号的业务员给对应队列号的客户办理业务
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			// 筛选消息的类型
			switch (msg.what) {
			case LOGIN_MSG:
				// 获得要传递的消息
				String message = (String) msg.obj;
				// 进行显示
				Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT)
						.show();
				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// 获取控件
		etName = (EditText) findViewById(R.id.etName);
		etPwd = (EditText) findViewById(R.id.etPwd);
		ivPic = (ImageView) findViewById(R.id.ivPic);
	}

	/**
	 * 登录
	 * 
	 * @param v
	 */
	public void login(View v) {
		// 开启线程来发起网络请求(耗时的操作需要开启新线程,比如网络连接和解析xml等,能有效的解决ANR的问题)
		new Thread(new Runnable() {

			@Override
			public void run() {
				BufferedReader reader = null;
				HttpURLConnection connection = null;

				String name = etName.getText().toString();// 用户名
				String pwd = etPwd.getText().toString();// 密码

				try {
					// 1.准备需要访问的网址
					//其中000.000.0.000是自己电脑的ip地址,URL中不能包含包名
					URL url = new URL(
							"http://000.000.0.000:8080/NetWorkDemo/LoginServlet?name="
									+ name + "&pwd=" + pwd);
					// 2.创建连接
					connection = (HttpURLConnection) url.openConnection();
					// 3.获得提交方法
					connection.setRequestMethod("GET");
					// 4.设置连接超时时间,单位:毫秒
					connection.setConnectTimeout(8000);
					// 5.设置读取超时时间,单位:毫秒
					connection.setReadTimeout(8000);

					// 获取响应吗
					int code = connection.getResponseCode();
					if (code == 200) {
						// 6.提交请求
						InputStream in = connection.getInputStream();
						// 7.从信息流中获取信息
						reader = new BufferedReader(new InputStreamReader(in));

						StringBuilder sb = new StringBuilder();
						String line;
						while ((line = reader.readLine()) != null) {
							sb.append(line);
						}

						// 使用异步消息处理机制(Handler机制,和银行柜台办理业务流程类似)
						// 1.创建消息(类似于去银行办理业务的客户)
						Message message = Message.obtain();
						// 2.设置消息类型(客户的队列号)
						message.what = LOGIN_MSG;
						// 3.设置消息内容(客户要办理的业务)
						message.obj = sb.toString().trim();
						// 5.发送消息(在上一个客户业务办理完成后,柜台呼叫下一个客户来办理业务)
						handler.sendMessage(message);
					} else if (code == 404) {
						Log.i("接收到的信息", "404");
					} else if (code == 500) {
						Log.i("接收到的信息", "500");
					}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.i("提示1", e.toString());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.i("提示2", e.toString());
				}

			}
		}).start();
	}
	
	/**
	 * xUtil框架Get方式提交请求
	 * 
	 * @param v
	 */
	public void xGetLogin(View v) {
		HttpUtils hu = new HttpUtils();
		String name = etName.getText().toString();
		String pwd = etPwd.getText().toString();
		
		//其中000.000.0.000是自己电脑的ip地址,URL中不能包含包名
		hu.send(HttpMethod.GET,
				"http://000.000.0.000:8080/NetWorkDemo/LoginServlet?name="
									+ name + "&pwd=" + pwd, new RequestCallBack<String>() {

					/**
					 * 成功或者失败
					 */
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// TODO Auto-generated method stub
						String message = responseInfo.result;
						Toast.makeText(MainActivity.this, message,
								Toast.LENGTH_SHORT).show();
					}

					/**
					 * 异常处理
					 */
					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub
						Log.e("错误信息", msg);
					}

				});

	}

	/**
	 * xUtil框架Post方式提交请求
	 * 
	 * @param v
	 */
	public void xPostLogin(View v) {
		HttpUtils hu = new HttpUtils();
		String name = etName.getText().toString();
		String pwd = etPwd.getText().toString();

		// 传递参数,以键值对的方式传值
		RequestParams rp = new RequestParams();
		rp.addBodyParameter("name", name);
		rp.addBodyParameter("pwd", pwd);
		
		//其中000.000.0.000是自己电脑的ip地址,URL中不能包含包名
		hu.send(HttpMethod.POST,
				"http://000.000.0.000:8080/NetWorkDemo/LoginServlet", rp,
				new RequestCallBack<String>() {

					/**
					 * 成功或者失败
					 */
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// TODO Auto-generated method stub
						String message = responseInfo.result;
						Toast.makeText(MainActivity.this, message,
								Toast.LENGTH_SHORT).show();
					}

					/**
					 * 异常处理
					 */
					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub
						Log.e("错误信息", msg);
					}

				});
	}


}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值