Ref:http://blog.csdn.net/zuolongsnail/article/details/6373051

Android应用经常会和服务器端交互,这就需要手机客户端发送网络请求,下面介绍四种常用网络请求方式,我这边是通过Android单元测试来完成这四种方法的,还不清楚Android的单元测试的同学们请看Android开发技巧总结中的Android单元测试的步骤一文。

java.net包中的HttpURLConnection类

Get方式:

// Get方式请求

public static void requestByGet() throws Exception {

String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";

// 新建一个URL对象

URL url = new URL(path);

// 打开一个HttpURLConnection连接

HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

// 设置连接超时时间

urlConn.setConnectTimeout(5 * 1000);

// 开始连接

urlConn.connect();

// 判断请求是否成功

if (urlConn.getResponseCode() == HTTP_200) {

// 获取返回的数据

byte[] data = readStream(urlConn.getInputStream());

Log.i(TAG_GET, "Get方式请求成功,返回数据如下:");

Log.i(TAG_GET, new String(data, "UTF-8"));

} else {

Log.i(TAG_GET, "Get方式请求失败");

}

// 关闭连接

urlConn.disconnect();

}

Post方式:

// Post方式请求

public static void requestByPost() throws Throwable {

String path = "https://reg.163.com/logins.jsp";

// 请求的参数转换为byte数组

String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")

+ "&pwd=" + URLEncoder.encode("android", "UTF-8");

byte[] postData = params.getBytes();

// 新建一个URL对象

URL url = new URL(path);

// 打开一个HttpURLConnection连接

HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

// 设置连接超时时间

urlConn.setConnectTimeout(5 * 1000);

// Post请求必须设置允许输出

urlConn.setDoOutput(true);

// Post请求不能使用缓存

urlConn.setUseCaches(false);

// 设置为Post请求

urlConn.setRequestMethod("POST");

urlConn.setInstanceFollowRedirects(true);

// 配置请求Content-Type

urlConn.setRequestProperty("Content-Type",

"application/x-www-form-urlencode");

// 开始连接

urlConn.connect();

// 发送请求参数

DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());

dos.write(postData);

dos.flush();

dos.close();

// 判断请求是否成功

if (urlConn.getResponseCode() == HTTP_200) {

// 获取返回的数据

byte[] data = readStream(urlConn.getInputStream());

Log.i(TAG_POST, "Post请求方式成功,返回数据如下:");

Log.i(TAG_POST, new String(data, "UTF-8"));

} else {

Log.i(TAG_POST, "Post方式请求失败");

}

}

org.apache.http包中的HttpGet和HttpPost类

Get方式:

// HttpGet方式请求

public static void requestByHttpGet() throws Exception {

String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";

// 新建HttpGet对象

HttpGet httpGet = new HttpGet(path);

// 获取HttpClient对象

HttpClient httpClient = new DefaultHttpClient();

// 获取HttpResponse实例

HttpResponse httpResp = httpClient.execute(httpGet);

// 判断是够请求成功

if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {

// 获取返回的数据

String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");

Log.i(TAG_HTTPGET, "HttpGet方式请求成功,返回数据如下:");

Log.i(TAG_HTTPGET, result);

} else {

Log.i(TAG_HTTPGET, "HttpGet方式请求失败");

}

}

Post方式:

// HttpPost方式请求

public static void requestByHttpPost() throws Exception {

String path = "https://reg.163.com/logins.jsp";

// 新建HttpPost对象

HttpPost httpPost = new HttpPost(path);

// Post参数

List<NameValuePair> params = new ArrayList<NameValuePair>();

params.add(new BasicNameValuePair("id", "helloworld"));

params.add(new BasicNameValuePair("pwd", "android"));

// 设置字符集

HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);

// 设置参数实体

httpPost.setEntity(entity);

// 获取HttpClient对象

HttpClient httpClient = new DefaultHttpClient();

// 获取HttpResponse实例

HttpResponse httpResp = httpClient.execute(httpPost);

// 判断是够请求成功

if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {

// 获取返回的数据

String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");

Log.i(TAG_HTTPGET, "HttpPost方式请求成功,返回数据如下:");

Log.i(TAG_HTTPGET, result);

} else {

Log.i(TAG_HTTPGET, "HttpPost方式请求失败");

}

}

以上是一些部分代码,测试的时候在测试类中运行对应的测试方法即可。

Android进阶(一)几种网络请求方式详解的更多相关文章

  1. VirtualBox的四种网络连接方式详解

    VirtualBox中有4中网络连接方式: 1. NAT 2. Bridged Adapter 3. Internal 4. Host-only Adapter VMWare中有三种,其实他跟VMWa ...

  2. JAVA中的四种JSON解析方式详解

    JAVA中的四种JSON解析方式详解 我们在日常开发中少不了和JSON数据打交道,那么我们来看看JAVA中常用的JSON解析方式. 1.JSON官方 脱离框架使用 2.GSON 3.FastJSON ...

  3. Android学习笔记_50_(转 四种加载方式详解(standard singleTop singleTask singleInstance)

    Android之四种加载方式 (http://marshal.easymorse.com/archives/2950 图片) 在多Activity开发中,有可能是自己应用之间的Activity跳转,或 ...

  4. Android 四种加载方式详解(standard singleTop singleTask singleInstance) .

    Android之四种加载方式 (http://marshal.easymorse.com/archives/2950 图片) 在多Activity开发中,有可能是自己应用之间的Activity跳转,或 ...

  5. VMware 虚拟机的网络连接方式详解

         VMWare提供了三种工作模式,它们是bridged(桥接模式).NAT(网络地址转换模式)和host-only(主机模式).要想在网络管理和维护中合理应用它们,你就应该先了解一下这三种工作 ...

  6. 一次完整的HTTP网络请求过程详解

    0.  前言 从我们在浏览器的地址栏输入http://blog.csdn.net/seu_calvin后回车,到我们看到该博客的主页,这中间经历了什么呢?简单地回答这个问题,大概是经历了域名解析.TC ...

  7. 「JavaScript」四种跨域方式详解

    超详细并且带 Demo 的 JavaScript 跨域指南来了! 本文基于你了解 JavaScript 的同源策略,并且了解使用跨域跨域的理由. 1. JSONP 首先要介绍的跨域方法必然是 JSON ...

  8. thinkphp四种url访问方式详解

    本文实例分析了thinkphp的四种url访问方式.分享给大家供大家参考.具体分析如下: 一.什么是MVC thinkphp的MVC模式非常灵活,即使只有三个中和一个也可以运行. M -Model 编 ...

  9. 「JavaScript」JS四种跨域方式详解

    原文地址https://segmentfault.com/a/1190000003642057 超详细并且带 Demo 的 JavaScript 跨域指南来了! 本文基于你了解 JavaScript ...

随机推荐

  1. C语言程序设计第二次作业0

    (一)改错题 1.输出带框文字:在屏幕上输出以下3行信息. ************* Welcome ************* 源程序 include int mian() { printf(&q ...

  2. 39. Combination Sum(medium, backtrack 的经典应用, 重要)

    Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique c ...

  3. 文件上传,服务端压缩文件方法,重点是png与gif图片的压缩,保证了透明度与动画

    /// <summary> /// 上传文件帮助类 /// </summary> public class ImageUploadHelper { #region SaveVi ...

  4. android注解入门 并来自己写一个框架

    介绍 这里我带大家来学习一下注解 并且用来写下一个模仿xUtils3 中View框架 此框架 可以省略activity或者fragment的 findViewById 或者设置点击事件的烦恼 我正参加 ...

  5. Openstack: MP-BIOS bug: 8254 timer not connected to IO-APIC

    Issue: After you import an linux image into openstack and run an instance of it, you may find that t ...

  6. ubuntu蓝牙音响配对成功但在声音设置中无法设置 解决

    ubuntu蓝牙音响配对成功但在声音设置中无法设置 解决 首先,连接蓝牙 但是,在声音设置中如下: 都没有发现设备??? 打开终端输入: ~$ pactl load-module module-blu ...

  7. SpringMVC常用配置(二),最简洁的配置实现文件上传

    Spring.SpringMVC持续介绍中,基础配置前面已经介绍了很多,如果小伙伴们还不熟悉可以参考这几篇文章: 1.Spring基础配置 2.Spring常用配置 3.Spring常用配置(二) 4 ...

  8. Python 2.7的字典实现简化版(C语言)

    这是一个能自动调整大小的哈希字典,外部接口实现了下列功能. 1.字典级别: 创建字典 dict_new 归零字典 dict_clear 2.键值级别: 查找 dict_search 强制查找 dict ...

  9. C++ 中const作用

    一.对const与#define的特点及区别的理解 #define只是用来做文本替换的,#define常量的生命周期止于编译期,它存在于程序的代码段,在实际程序中它只是一个常数,一个命令中的参数,并没 ...

  10. github pages + Hexo + 域名绑定搭建个人博客

    环境 Windows 10(64 位) Git-2.7.4-64-bit node-v4.4.7-x64 如果上述软件已经安装的,跳过,没有安装的下载安装. 1,git下载安装(https://git ...