Android中的Http通信(三)之get、post传递参数到服务器
16lz
2021-01-23
如果你看到这一片文章,但是你还对http协议的基本知识以及通过url获取网络数据还不是很了解,请先看一下上面两篇文章:Android中的Http通信(一)之Http协议基本知识、 Android中的Http通信(二)之根据Url读取网络数据。
本文主要介绍的是通过http中的GET方式和POST方式上传数据到服务器,其中涉及到解决服务器乱码问题。本文需要服务器和Android前端配合,由于这里是写Android方面的问题,后台服务器我就写了一个简单的demo,在文章最后大家可以自行下载,这里不在累述(其实是本人的服务器的功底.....)。废话不多说,直接开干。
遵循上一篇的习惯,先来一个布局吧:
很简单,不做任何介绍,如果看不懂的话,先补习补习,再往下看。
下面是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();@Overrideprotected 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() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubString 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() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubLog.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();}});}@Overridepublic 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;}@Overridepublic 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() {@Overridepublic void run() {// TODO Auto-generated method stubresponse.setText(buffer.toString());}});} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.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() {@Overridepublic void run() {// TODO Auto-generated method stubresponse.setText(buffer.toString());}});} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void run() {// TODO Auto-generated method stubif (tag == 1) http://doGet();else if (tag == 2)doPost();}}
GET、POST传递参数的时候的区别:
两者的URL:
GET:基本的url+参数的拼接;
POST:基本的url
是否携带输出流:
GET:不需要;
POST:参数的拼接然后转化为字节数组
服务器项目:http://download.csdn.net/detail/u014544193/9337713
客户端项目:http://download.csdn.net/detail/u014544193/9337733
更多相关文章
- Android通过JSON数据格式和java服务后台进行数据交互
- Android (安卓数据的五种存储方式)
- 基于xml类型的压缩数据流的android获取天气的方法
- Android使用Http连接服务器,解析JSON, XML等教程
- 王家林最受欢迎的一站式云计算大数据和移动互联网解决方案课程 V
- android 从文件制定位置读取数据
- Android---8---Intent及使用Intent传递数据
- 还原Android彩信数据库
- 一种Android数据请求框架