Android中的Http通信(三)之get、post传递参数到服务器

本文介绍了如何使用HTTP的GET和POST方法在Android应用中实现登录功能,并解决了服务器乱码问题。通过布局和代码示例展示了用户输入用户名和密码后,GET和POST两种方式如何将数据传送到服务器并接收响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果你看到这一片文章,但是你还对http协议的基本知识以及通过url获取网络数据还不是很了解,请先看一下上面两篇文章:Android中的Http通信(一)之Http协议基本知识 Android中的Http通信(二)之根据Url读取网络数据

本文主要介绍的是通过http中的GET方式和POST方式上传数据到服务器,其中涉及到解决服务器乱码问题。本文需要服务器和Android前端配合,由于这里是写Android方面的问题,后台服务器我就写了一个简单的demo,在文章最后大家可以自行下载,这里不在累述(其实是本人的服务器的功底.....大哭大哭大哭)。废话不多说,直接开干。

遵循上一篇的习惯,先来一个布局吧:

<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" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="用户名:肖运飞\n密码:123456" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="用户名:" />

        <EditText
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="用户名" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="密码:" />

        <EditText
            android:id="@+id/pwd"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="密码" />
    </LinearLayout>

    <Button
        android:id="@+id/get_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="GET 登录" />
    
    <Button
        android:id="@+id/post_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="POST 登录" />

    <TextView
        android:id="@+id/response"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" />

</LinearLayout>

很简单,不做任何介绍,如果看不懂的话,先补习补习,再往下看敲打

下面是Ativity中的代码:

package com.example.http;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 测试http的get、post的类
 * 
 * @author xiaoyf
 * 
 */
public class MainActivity extends Activity {

	private EditText name;
	private EditText pwd;
	private Button get_btn;
	private Button post_btn;
	private TextView response;
	private Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		name = (EditText) findViewById(R.id.name);
		pwd = (EditText) findViewById(R.id.pwd);
		get_btn = (Button) findViewById(R.id.get_btn);
		post_btn = (Button) findViewById(R.id.post_btn);
		response = (TextView) findViewById(R.id.response);

		get_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String url = "http://192.168.1.2:8080/WebProject/MyServlet";
				new HttpThread(url, name.getText().toString(), pwd.getText()
						.toString(), response, handler, 1).start();
			}
		});

		post_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Log.d("bbb", "onClick");
				String url = "http://192.168.1.2:8080/WebProject/MyServlet";
				new HttpThread(url, name.getText().toString(), pwd.getText()
						.toString(), response, handler, 2).start();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

下面是GET、POST传递参数 的核心代码,也是本篇的核心。

package com.example.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.os.Handler;
import android.util.Log;
import android.webkit.WebView;
import android.widget.TextView;

/**
 * 测试http的get、post的线程
 * 
 * @author xiaoyf
 * 
 */
public class HttpThread extends Thread {
	private final static int CONNECT_OUT_TIME = 5000;
	private String url;
	private String name;
	private String pwd;
	private TextView response;

	private Handler handler;
	/**
	 * tag=1:默认,get方式;tag=2:post方式
	 */
	private int tag = 1;

	public HttpThread() {
		super();
	}

	public HttpThread(String url, String name, String pwd, TextView response,
			Handler handler, int tag) {
		super();
		this.url = url;
		this.name = name;
		this.pwd = pwd;
		this.response = response;
		this.handler = handler;
		this.tag = tag;
	}

	public void doGet() {
		// 如果服务器没有转码的时候,我们可以设置,防止乱码
		// name = URLEncoder.encode(name, "utf-8");
		// pwd = URLEncoder.encode(pwd, "utf-8");

		url += "?name=" + name + "&pwd=" + pwd;
		try {
			// 第一步:创建必要的URL对象
			URL httpUrl = new URL(url);
			// 第二步:根据URL对象,获取HttpURLConnection对象
			HttpURLConnection connection = (HttpURLConnection) httpUrl
					.openConnection();
			// 第三步:为HttpURLConnection对象设置必要的参数(是否允许输入数据、连接超时时间、请求方式)
			connection.setConnectTimeout(CONNECT_OUT_TIME);
			connection.setReadTimeout(CONNECT_OUT_TIME);
			connection.setRequestMethod("GET");
			connection.setDoInput(true);
			// 第四步:开始读取服务器返回数据
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			final StringBuffer buffer = new StringBuffer();
			String str = null;
			while ((str = reader.readLine()) != null) {
				buffer.append(str);
			}
			reader.close();

			handler.post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					response.setText(buffer.toString());
				}
			});

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void doPost() {

		try {
			// 第一步:创建必要的URL对象
			URL httpUrl = new URL(url);
			// 第二步:根据URL对象,获取HttpURLConnection对象
			HttpURLConnection connection = (HttpURLConnection) httpUrl
					.openConnection();
			// 第三步:为HttpURLConnection对象设置必要的参数(是否允许输入数据、连接超时时间、请求方式)
			connection.setConnectTimeout(CONNECT_OUT_TIME);
			connection.setReadTimeout(CONNECT_OUT_TIME);
			connection.setRequestMethod("POST");
			connection.setDoInput(true);
			// 第四步:向服务器写入数据
			OutputStream out = connection.getOutputStream();
			String content = "name=" + name + "&pwd=" + pwd;// 无论服务器转码与否,这里不需要转码,因为Android系统自动已经转码为utf-8啦
			out.write(content.getBytes());
			out.flush();
			out.close();
			// 第五步:开始读取服务器返回数据
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			final StringBuffer buffer = new StringBuffer();
			String str = null;
			while ((str = reader.readLine()) != null) {
				buffer.append(str);
			}
			reader.close();

			handler.post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					response.setText(buffer.toString());
				}
			});

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		if (tag == 1) http://
			doGet();
		else if (tag == 2)
			doPost();
	}

}

GET、POST传递参数的时候的区别:

两者的URL:

GET:基本的url+参数的拼接;

POST:基本的url

是否携带输出流:

GET:不需要;

POST:参数的拼接然后转化为字节数组


服务器项目:http://download.youkuaiyun.com/detail/u014544193/9337713

客户端项目:http://download.youkuaiyun.com/detail/u014544193/9337733

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值