Android开发中的几种网络请求方式详解

作者:Snail 时间:2021-06-01 17:45:21 

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

Java.NET包中的HttpURLConnection类

Get方式:


// Get方式请求
public static void requestByGet() throws Exception {
String path = "https://www.jb51.net/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://www.jb51.net/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://www.jb51.net/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://www.jb51.net/";
// 新建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,网络请求
0
投稿

猜你喜欢

  • java数学工具类Math详解(round方法)

    2022-09-10 17:01:00
  • 快速搭建Spring Boot+MyBatis的项目IDEA(附源码下载)

    2023-10-24 18:29:53
  • mybatis源码解读之executor包懒加载功能 

    2022-09-17 00:28:05
  • Spring实战之注入集合值操作示例

    2023-03-04 04:02:53
  • Spring Data JPA 之 JpaRepository的使用

    2023-11-24 21:23:40
  • SpringCloud Zuul实现负载均衡和熔断机制方式

    2023-08-23 11:56:43
  • 关于国际化、OGNL表达式语言

    2023-09-04 15:20:45
  • SpringBoot工程搭建打包、启动jar包和war包的教程图文详解

    2022-05-04 22:09:10
  • c#项目将dll打包到exe中的步骤

    2021-06-21 14:44:25
  • eclipse中自动生成javadoc文档的方法

    2022-04-08 17:54:12
  • npoi2.0将datatable对象转换为excel2007示例

    2021-07-15 12:47:30
  • 跳一跳自动跳跃C#代码实现

    2023-02-19 11:12:46
  • Spring JPA 错题集解决案例

    2022-03-26 22:44:03
  • spring @Conditional的使用与扩展源码分析

    2022-01-09 05:52:57
  • 详解Spring-boot中读取config配置文件的两种方式

    2021-07-04 15:52:55
  • Java Maven settings.xml中私有仓库配置详解

    2022-02-19 15:36:50
  • eclipse+maven+spring mvc项目基本搭建过程

    2022-12-18 03:50:52
  • Thymeleaf 3.0 自定义标签方言属性的实例讲解

    2023-03-24 20:40:23
  • Java详细讲解堆排序与时间复杂度的概念

    2023-10-20 02:00:11
  • 使用IDEA将Java/Kotliin工程导出Jar包的正确姿势

    2022-10-18 17:39:34
  • asp之家 软件编程 m.aspxhome.com