Android中post和get的提交方式【三种】

向服务器提交数据有两种方式,post和get。两者的区别主要有三点,安全性、长度限制、数据结构。其中get请求安全性相比较而言较差,数据长度受浏览器地址栏限制,没有方法体。两种都是较为重要的数据提交方式。现简单介绍一下三种post和get的提交方式。无论是哪种方法实现post和get,get 的访问路径都要携带数据,而post提交是把数据放在方法体中。

普通方法实现get/post提交:   

严格遵照Http协议进行数据传输。在安卓开发环境下,由于主线程不能进行网络访问,因此需要在开启一个子线程向服务器提交数据。为了更加直观的观察数据,可以在程序屏幕上显示服务器反馈信息。又由于子线程无法更改UI界面,因此需要引入Hnndler代理器。实现get/post提交基本步骤就是,获取URL路径,根据路径得到Http连接,用HttpURLConnection对象设置相关的http配置信息、提交方式以及获取反馈码。当响应码为200时表示提交成功,可以通过HttpURLConnection以流的形式获取反馈信息。

普通GRT提交方式:

public void load(View view){
 final String qq = et_qq.getText().toString().trim();
 final String pwd = et_pwd.getText().toString().trim();
 if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) {
  Toast.makeText(MainActivity.this, "qq号或密码为空", 0).show();
  return;
 }
 final String path = "http://192.168.1.114:8080/qqload/qqload?qq=" + qq
  + "&pwd=" + pwd;
 new Thread() {
  public void run() {
  try {
   URL url = new URL(path);
   HttpURLConnection conn = (HttpURLConnection) url
    .openConnection();
   conn.setRequestMethod("GET");
   conn.setReadTimeout(5000);
   int code = conn.getResponseCode();
   if (code == 200) {
   InputStream is = conn.getInputStream();
   String result = StreamTools.ReadStream(is);
   Message msg = Message.obtain();
   msg.what = SUCCESS;
   msg.obj = result;
   handler.sendMessage(msg);
   } else {
   Message msg = Message.obtain();
   msg.what = ERROR1;
   handler.sendMessage(msg);
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Message msg = Message.obtain();
   msg.what = ERROR2;
   handler.sendMessage(msg);
  }
  }
 }.start();
 }

普通POST提交方式:

public void load(View view){
 final String qq = et_qq.getText().toString().trim();
 final String pwd = et_pwd.getText().toString().trim();
 if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) {
  Toast.makeText(MainActivity.this, "qq号或密码为空", 0).show();
  return;
 }
 final String path = "http://192.168.1.114:8080/qqload/qqload";
 new Thread() {
  public void run() {
  try {
   URL url = new URL(path);
   HttpURLConnection conn = (HttpURLConnection) url
    .openConnection();
   conn.setRequestMethod("POST");
   conn.setReadTimeout(5000);
   conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
   String data = "qq="+URLEncoder.encode(qq,"utf-8")+"&pwd=" + URLEncoder.encode(pwd,"utf-8"); 
   conn.setRequestProperty("Content-Length",String.valueOf(data.length()));
   conn.setDoOutput(true);
   conn.getOutputStream().write(data.getBytes());
   int code = conn.getResponseCode();
   if (code == 200) {
   InputStream is = conn.getInputStream();
   String result = StreamTools.ReadStream(is);
   Message msg = Message.obtain();
   msg.what = SUCCESS;
   msg.obj = result;
   handler.sendMessage(msg);
   } else {
   Message msg = Message.obtain();
   msg.what = ERROR1;
   handler.sendMessage(msg);
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Message msg = Message.obtain();
   msg.what = ERROR2;
   handler.sendMessage(msg);
  }
  }
 }.start();
 }

用httpclien实现get/post提交的只需要一下几个步骤:

1.创建HttpClient对象,实现打开浏览器的功能

 HttpClient client = new DefaultHttpClient();

2.输入地址或者数据 ,用到HttpGet()或HttpPost(),传入要访问的路径,得到HttpGet或HttpPost对象。

 HttpGet  httpGet = new HttpGet(path);

3.把获得的HttpGet或HttpPost对象发送到服务器,实现敲回车的功能,得到HttpResponse对象。

 HttpResponse response = client.execute(httpGet);

4.得到HttpResponse对象获取状态行中的状态码,判断状态码状态码。

 int code = response.getStatusLine().getStatusCode();

5.同样用HttpResponse对象获取相应内容,存入流对象。最后将得到的流对象转为字符串进行显示。

 InputStream is = response.getEntity().getContent();

其中要注意的一点是用post请求时要传递值所以要多出一个步骤。具体而言,先创建一个list集合,集合的泛型用NameValuePair表示,类似于键值对的形式存储要传递的数据。接着向集合中添加要提交数据。最后用HttpPost对象把集合存入请求体中。

用HttpClient实现GET提交:

public void load(View view){
 final String qq = et_qq.getText().toString().trim();
 final String pwd = et_pwd.getText().toString().trim();
 if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) {
  Toast.makeText(MainActivity.this, "qq号或密码为空", 0).show();
  return;
 }
 final String path = "http://192.168.1.114:8080/qqload/qqload?qq=" + qq
  + "&pwd=" + pwd;
 new Thread() {
  public void run() {
  try {
   HttpClient client = new DefaultHttpClient();
   HttpGet httpget = new HttpGet(path);
   HttpResponse response = client.execute(httpget);
   int code = response.getStatusLine().getStatusCode();
   if (code == 200) {
   InputStream is = response.getEntity().getContent();
   String result = StreamTools.ReadStream(is);
   Message msg = Message.obtain();
   msg.what = SUCCESS;
   msg.obj = result;
   handler.sendMessage(msg);
   } else {
   Message msg = Message.obtain();
   msg.what = ERROR1;
   handler.sendMessage(msg);
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Message msg = Message.obtain();
   msg.what = ERROR2;
   handler.sendMessage(msg);
  }
  }
 }.start();
 }

用HttpClient实现POST提交:   

 public void load(View view){
 final String qq = et_qq.getText().toString().trim();
 final String pwd = et_pwd.getText().toString().trim();
 if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) {
  Toast.makeText(MainActivity.this, "qq号或密码为空", 0).show();
  return;
 }
 final String path = "http://192.168.1.114:8080/qqload/qqload";
 new Thread() {
  public void run() {
  try {
   HttpClient client = new DefaultHttpClient();
   HttpPost httppost = new HttpPost(path);
   List<NameValuePair> parameter = new ArrayList();
   parameter.add(new BasicNameValuePair("qq", qq));
   parameter.add(new BasicNameValuePair("pwd", pwd));
   httppost.setEntity(new UrlEncodedFormEntity(parameter,"utf-8"));
   HttpResponse response = client.execute(httppost);
   int code = response.getStatusLine().getStatusCode();
   if (code == 200) {
   InputStream is = response.getEntity().getContent();
   String result = StreamTools.ReadStream(is);
   Message msg = Message.obtain();
   msg.what = SUCCESS;
   msg.obj = result;
   handler.sendMessage(msg);
   } else {
   Message msg = Message.obtain();
   msg.what = ERROR1;
   handler.sendMessage(msg);
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Message msg = Message.obtain();
   msg.what = ERROR2;
   handler.sendMessage(msg);
  }
  }
 }.start();
 }

使用开源框架实现get/post提交:

利用框架实现get/post提交不需要再开启子线程。直接在主线程进行get/post的提交,大大的减少了工作量。但操作前需要导包。然后直接创建一个AsyncHttpClient对象,用AsyncHttpClient对象的post方法和get方法,发送请求,并在AsyncHttpResponseHandler()对象中获得相应信息。同样若是post请求,仍旧需要传递值。这里可以用RequestParams对象添加要传递的值。

在文件下添加jar包:

用开源框架实现GET提交:

 public void load(View view){
 final String qq = et_qq.getText().toString().trim();
 final String pwd = et_pwd.getText().toString().trim();
 if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) {
  Toast.makeText(MainActivity.this, "qq号或密码为空", 0).show();
  return;
 }
 final String path = "http://192.168.1.114:8080/qqload/qqload?qq=" + qq
  + "&pwd=" + pwd;
 AsyncHttpClient client = new AsyncHttpClient();
 client.get(path, new AsyncHttpResponseHandler() {
  
  @Override
  public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
  // TODO Auto-generated method stub
  tv_result.setText(new String(responseBody));
  }
  
  @Override
  public void onFailure(int statusCode, Header[] headers,
   byte[] responseBody, Throwable error) {
  // TODO Auto-generated method stub
  tv_result.setText("错误原因:" + new String(responseBody));
  }
 });
 }

用开源框架实现POST请求:

public void load(View view){
 final String qq = et_qq.getText().toString().trim();
 final String pwd = et_pwd.getText().toString().trim();
 if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) {
  Toast.makeText(MainActivity.this, "qq号或密码为空", 0).show();
  return;
 }
 final String path = "http://192.168.1.114:8080/qqload/qqload";
 AsyncHttpClient client = new AsyncHttpClient();
 RequestParams params = new RequestParams();
 params.add("qq", qq);
 params.add("pwd", pwd);
 client.post(path,params,new AsyncHttpResponseHandler() {
  
  @Override
  public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
  // TODO Auto-generated method stub
  tv_result.setText(new String(responseBody));
  }
  
  @Override
  public void onFailure(int statusCode, Header[] headers,
   byte[] responseBody, Throwable error) {
  // TODO Auto-generated method stub
  tv_result.setText(new String(responseBody));
  }
 });
 }

通过以上任何一种方式可以实现的功能是,从安卓手机端提交数据到服务器端,服务器端进行判断,并返回相应的结果。三种方式各有利弊,实现效果相同,在实际的使用过程中可以根据本身的需要进行选择。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持呐喊教程!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。