Android有这几种方式,可以提交数据到服务器,他们是怎么使用的呢,这里我们来探讨一下。

这里的例子用的都是提交客户端的用户名及密码,同时本节用到的StreamTools.readInputStream(is);作用是把输入流转化为字符串,是一个公共类。我在前面介绍过了。http://www.cnblogs.com/fengtengfei/p/3969520.html,这里就不在重复的说明了。

第一种:GET

关键部分是:

首先我们用URL包装访问的路径,由于是get请求,在学习javaWEB的时候我们就以及知道了,路径中要把提交的参数拼装。

然后我们openConnection(),其返回的是HttpURLConnection对象,拿到这个对象我们就可以进行相关参数,及超时的设置,以及获取服务器的返回码了。

			URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();

example:

 public static String loginByGet(String username,String password) {
//提交数据到发服务器
String path = null;
try {
path = "http://192.168.254.100:8080/web/LoginServlet?username="+URLEncoder.encode(username,"utf-8")+"&password="+password;
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} try {
URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET"); int code = conn.getResponseCode();
if(code==200){
//请求成功
InputStream is = conn.getInputStream();
String result = StreamTools.readInputStream(is); return result;
}else{
return null;
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} }

第二种:Post

在网页的get与post的请求的对比中我们知道post比get多了几个参数,所以这里我们也是要对相关参数进行设置的,

首先我们要设置的是Content-type与Cotent-Length,

	           String data = "username="+URLEncoder.encode(username,"utf-8")+"&password="+password;
conn.setRequestProperty("Content-Type:", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length:", data.length()+"");

其次,post的方式,实际上是浏览器把数据写给服务器。所以我们要设置相关参数,让服务器允许我们有写的权限,

	          conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());

example:

 public static String loginByPost(String username,String password){
//POST提交数据到发服务器
String path = "http://192.168.254.100:8080/web/LoginServlet"; try {
URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
//准备数据,计算其长度
String data = "username="+URLEncoder.encode(username,"utf-8")+"&password="+password;
conn.setRequestProperty("Content-Type:", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length:", data.length()+"");
//post的方式,实际上是浏览器把数据写给服务器。
//允许写数据
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
System.out.println("2"); int code = conn.getResponseCode(); if(code==200){
//请求成功
InputStream is = conn.getInputStream();
String result = StreamTools.readInputStream(is); return result;
}else{
return null;
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} }

第三种:httpclientget

使用步骤是,我们首先要实例化一个HttpClient的对象,同时也要实例一个HttpGet的对象,让HttpClient的对象去execute(HttpGet的对象),这时我们可以得到HttpResponse的对象,二者就是服务器的返回的对象,所以区别就在这里了。

这里的返回码是这样获得的response.getStatusLine().getStatusCode();使用中要注意。

example:

public static String loginByHttpClientGet(String username,String password){
try {
HttpClient client = new DefaultHttpClient();
String path = "http://192.168.254.100:8080/web/LoginServlet?username="
+URLEncoder.encode(username)+"&password="+URLEncoder.encode(password);
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.readInputStream(is); return result;
}else{
return null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} }

第四种:httpclientpost

采用HttpClientPost的方式与HttpClientGet的方式的区别是HttpPost要指定提交的数据实体,而这里的实现就像是map,所以对于参数较多的时候,这种方式是最为便捷的。

	                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));

example:

public static String loginByHttpClientPost(String username,String password){
try {
HttpClient client = new DefaultHttpClient();
String path = "http://192.168.254.100:8080/web/LoginServlet";
HttpPost post = new HttpPost();
//指定要提交的数据实体
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode();
if(code==200){
//请求成功
InputStream is = response.getEntity().getContent();
String result = StreamTools.readInputStream(is); return result;
}else{
return null;
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}

作者:Darren

微博:@IT_攻城师

出处:http://www.cnblogs.com/fengtengfei/

Android数据与服务器交互的GET,POST,HTTPGET,HTTPPOST的使用的更多相关文章

  1. Android和FTP服务器交互,上传下载文件(实例demo)

    今天同学说他备份了联系人的数据放在一个文件里,想把它存到服务器上,以便之后可以进行下载恢复..于是帮他写了个上传,下载文件的demo 主要是 跟FTP服务器打交道-因为这个东东有免费的可以身亲哈 1. ...

  2. 20171018 微信小程序客户端数据和服务器交互

    -- 时常在想,怎么样才能把知识写的清晰,其实是我理解的不够清晰 微信小程序其实是一个客户端页面,也是需要和服务器交互才能体现数据. 1 --服务器搭建Web API :MVC4 中的一个模板, 如下 ...

  3. java攻城狮之路(Android篇)--与服务器交互

    一.图片查看器和网页源码查看器 在输入地址的是不能输入127.0.0.1 或者是 localhost.ScrollView :可以看成一个滚轴 可以去包裹很多的控件在里面 练习1(图片查看器): pa ...

  4. Android客户端与服务器交互中的token

    学习Token Token是什么? Token是服务端生成的一串字符串,以作客户端进行请求的一个令牌,当第一次登录后,服务器生成一个Token便将此Token返回给客户端,以后客户端只需带上这个Tok ...

  5. Android 客户端与服务器交互

    在android中有时候我们不需要用到本机的SQLite数据库提供数据,更多的时候是从网络上获取数据,那么Android怎么从服务器端获取数据呢?有很多种,归纳起来有 一:基于Http协议获取数据方法 ...

  6. Android与PHP服务器交互

    转自:http://blog.csdn.net/ab_ba/article/details/7912424 服务器端:server.php 1 <?php 2         include(' ...

  7. android app与服务器交互

    package mydemo.mycom.demo2.service; import org.apache.http.HttpResponse; import org.apache.http.Name ...

  8. android笔记--与服务器交互更改简历状态

    private AsyncHttpClient asyncHttpClient; private Dialog dialog; /** * 改变简历状态 */ private void postcha ...

  9. Android客户端与服务器

    就是普通的服务器端编程,还不用写界面,其实还比服务器编程简单一些.跟J2EE一样的服务器,你android这一方面只要用json或者gson直接拿数据,后台的话用tomcat接受请求操作数据,功能不复 ...

随机推荐

  1. “打开ftp服务器上的文件夹时发生错误,请检查是否有权限访问该文件夹"

    阿里云虚拟主机上传网站程序 问题场景:网页制作完成后,程序需上传至虚拟主机 注意事项: 1.Windows系统的主机请将全部网页文件直接上传到FTP根目录,即 / . 2. 如果网页文件较多,上传较慢 ...

  2. 1.INFORMATION_SCHEMA简介

    1. INFORMATION_SCHEMA简介 INFORMATION_SCHEMA提供对数据库元数据的访问,有关MySQL服务器信息,例如数据库或表的名称,列的数据类型或访问权限. INFORMAT ...

  3. 深入Linux内核架构——简介与概述

    一.内核的任务 纯技术层面上,内核是硬件与软件的之间的一个中间层.作用是将应用程序的请求传递给硬件,并充当底层驱动程序,对系统中的各种设备和组件进行寻址. 从应用程序视角上看,内核可以被认为是一台增强 ...

  4. 条款21:必须返回对象时,别妄想返回其reference(Don't try to return a reference when you must return an object)

    NOTE: 1.绝不要返回pointer或reference 指向一个local stack 对象,或返回reference 指向一个heap-allocated对象,或返回pointer 或refe ...

  5. 如何在Python中显式释放内存?

    根据Python官方文档,您可以强制垃圾收集器释放未引用的内存gc.collect().例: import gc gc.collect() 所属网站分类: python高级 > 综合&其 ...

  6. centos7下安装Python3.7(与python2共存)

    2019-01-22   22:50:05 centos7默认安装的是python2.7,然而python2基本上要淘汰了,所以有必要安装最新的python3 python,g++这些工具一般安装在/ ...

  7. Java.lang.NoSuchMethodError: 后带 V/Z等字母的

    知道 Java.lang.NoSuchMethodError: 后带 V/Z等字母的 错误,一般都是 jar包冲突引起的,找到冲突的jar包,去掉一个就好

  8. JS获取所有LI中第三个<SPAN>

  9. 性能测试工具 - ab 简单应用

    之前知道一般网站性能可以通过 LoadRunner, JMeter, QTP 等相应的软件进行测试, 印象中本科学习 “软件测试” 这门课程时安装并使用过, LoadRunner等不是一个小软件, 安 ...

  10. 565. Array Nesting

    Problem statement: A zero-indexed array A consisting of N different integers is given. The array con ...