Android登录(GET提交和POST提交)

一、首先创建一个安卓项目,设置好布局

<LinearLayout 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:orientation="vertical"
    tools:context="com.aiyou.getpost.MainActivity" >

    <EditText
        android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名"
        android:textSize="30sp" />

    <EditText
        android:id="@+id/et_pass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        android:textSize="30sp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="click1"
        android:text="GET方式提交" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="click2"
        android:text="POST方式提交" />

</LinearLayout>

二、GET提交方式

1、因为服务器返回的数据都是流,为了方便,我们写一个工具类StreamTools,实现流到字符串的转换

package com.aiyou.getpost;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTools {

	public static String readString(InputStream in) throws Exception {
		
		//定义一个内存输出流
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		int len=-1;
		byte[]buffer=new byte[1024];//1kb
		while ((len=in.read(buffer))!=-1) {
			baos.write(buffer,0,len);			
		}
		in.close();
		String content=new String(baos.toByteArray());	
		return content;	
	}
}

2、返回的数据变成字符串后,我们通过toast提示我们访问成功和失败,由于子线程不能修改UI,所以我们再写一个方法showToast,通过runOnUiThread修改UI
public void showToast(final String content) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), content, 1).show();
			}
		});
	}

3、创建一个线程,重写run方法

new Thread() {
			public void run() {
				try {
					// 获取账号和密码
					String name = et_name.getText().toString().trim();
					String pass = et_pass.getText().toString().trim();
					// 定义get方式提交的路径;根据自己服务器上编写路径
					String path = "http://192.168.1.111/login/loginser?user="
							+ name + "&pass=" + pass + "";
					// 创建URL对象 指定我们要访问的网址
					URL url = new URL(path);
					// 拿到httpurlconnection对象 用于发送和接受数据
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					// 设置请求超时时间
					conn.setConnectTimeout(5000);// 5秒
					// 设置发送请求方式
					conn.setRequestMethod("GET");
					// 获取服务器返回的状态码
					int code = conn.getResponseCode();
					// 200表明请求成功
					if (code == 200) {
						// 获取服务器返回的数据,返回的数据都是流的形式
						InputStream in = conn.getInputStream();
						// 把inputstream转换成字符串
						String content = StreamTools.readString(in);
						// 显示
						showToast(content);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();

4、添加网络权限

 <uses-permission android:name="android.permission.INTERNET"/>

三、POST方式

1、2、4步骤同GET

3、post代码

new Thread() {
			public void run() {

				try {
					// 获取账号和密码
					String name = et_name.getText().toString().trim();
					String pass = et_pass.getText().toString().trim();
					// 组建post数据
					String data = "username="
							+ URLEncoder.encode(name, "utf-8") + "&pass="
							+ URLEncoder.encode(pass, "utf-8") + "";
					// 定义post方式提交的路径;根据自己服务器上编写路径
					String path = "http://192.168.1.111/login/loginser";
					// 创建URL对象 指定我们要访问的网址
					URL url = new URL(path);
					// 拿到httpurlconnection对象 用于发送和接受数据
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					// 设置请求超时时间
					conn.setConnectTimeout(5000);// 5秒
					// 设置发送请求方式
					conn.setRequestMethod("POST");
					// 设置头信息
					conn.setRequestProperty("Content-Type", "text/html");
					conn.setRequestProperty("Content-Length", data.length()
							+ "");

					// 组拼好数据以流的形式提交服务器
					conn.setDoOutput(true);// 设置一个标记允许输出
					conn.getOutputStream().write(data.getBytes());
					// 获取服务器返回的状态码
					int code = conn.getResponseCode();
					// 200表明请求成功
					if (code == 200) {
						// 获取服务器返回的数据,返回的数据都是流的形式
						InputStream in = conn.getInputStream();
						// 把inputstream转换成字符串
						String content = StreamTools.readString(in);
						// 把服务器返回的数据展示到toast上
						showToast(content);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			};

		}.start();
项目源码:https://download.csdn.net/download/qq_35951882/10367728

猜你喜欢

转载自blog.csdn.net/qq_35951882/article/details/80046568