Android 中的网络操作(HttpURLConnection)

Android 中的网络操作(HttpURLConnection)

[var1]

Android 程序最重要的模块就是网络部分,如何从网络上下载数据,如何将处理过的数据上传至网络,往往是 Android 程序的关键环节。Android 中对于网络操作的有很多很好用的框架,如 OkHttp、Velloy、Retrofit 等。但是今天我们来重点讲解一下 HttpURLConnection 这个抽象类。

[var1]

1、权限申请

Android 中要做跟网络相关的操作,一定需要在清单文件中申请网络权限,如下所示:

Android 9.0 之前,只需要在清单文件中加上这句话就可以了,但是Android 9.0对 http 请求进行了限制,所以仅仅上面这一句话是不够的。为了解除这个限制,我们需要创建安全配置文件,具体步骤如下:

在 res 文件夹下创建xml/network-security-config 文件

android 生成url对象 安卓设置url_数据

增加 cleartextTrafficPermitted 属性<?xml version="1.0" encoding="utf-8"?>

在 AndroidManifest.xml 的 Application 节点中申请android:networkSecurityConfig="@xml/network_security_config"

2、get 请求

我们从玩Android上面随便找一个 GET 请求的 API。json 数据格式如下所示:

android 生成url对象 安卓设置url_xml_02

现在我们来利用 HttpURLConnection 的 GET 请求来将上面这段 json 数据打印出来,具体代码如下所示:

private final String URL = "https://wanandroid.com/wxarticle/chapters/json";
// HttpURLConnection
private void get() {
try {
// 1.实例化一个URL对象
URL url = new URL(URL);
// 2.获取HttpURLConnection实例
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3.设置和请求相关的属性
// 请求方式
conn.setRequestMethod("GET");
// 请求超时时间
conn.setConnectTimeout(10 * 1000);
// 4.获取响应码 200:成功 404:未请求到指定资源 500:服务器异常
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
// 5.判断响应码并获取响应数据(响应的正文)
// 获取响应的流
// IO 操作
InputStream in = conn.getInputStream();
byte[] b = new byte[1024];
int len;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = in.read(b)) > -1) {
baos.write(b, 0, len);
}
String msg = baos.toString();
Log.e("MainActivityTAG", msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void myClick(View v) {
switch (v.getId()) {
// Android4.0 以后网络操作必须放在子线程中
case R.id.btn_get:
new Thread(){
@Override
public void run() {
super.run();
get();
}
}.start();
break;
}
}

控制台上面的数据如下,我们已经成功的打印出来了。

android 生成url对象 安卓设置url_数据_03

通过上述代码我们需要注意一下三点:

在清单文件中申请 INTERNET 权限

如果是 http 请求,需要创建安全配置文件 network-security-config

Android4.0 以后网络操作必须放在子线程中

3、post 请求

我们从玩Android上面找一个 POST 请求的 API。然后我们可以利用 HttpURLConnection 的 POST 请求来实现一个登陆功能。

android 生成url对象 安卓设置url_数据_04

具体代码实现如下所示:

private void post(String account, String password) {
try {
// 1.实例化一个URL对象
URL url = new URL("https://www.wanandroid.com/user/login");
// 2.获取HttpURLConnection实例
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3.设置和请求相关的属性
// 请求方式
conn.setRequestMethod("POST");
// 请求超时时间
conn.setConnectTimeout(10 * 1000);
// 设置允许输出
conn.setDoOutput(true);
// 设置提交数据的类型
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//获取输出流(请求正文)
OutputStream out = conn.getOutputStream();
//写数据
out.write(("username=" + account + "&password=" + password).getBytes());
//4.获取响应码 200:成功 404:未请求到指定资源 500:服务器异常
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
//5.判断响应码并获取响应数据(响应的正文)
//获取响应的流
InputStream in = conn.getInputStream();
byte[] b = new byte[1024];
int len;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//在循环中读取输入流
// in.read(b); // 该方法返回值是int类型数据,代表的是实际读到的数据长度
while ((len = in.read(b)) > -1) {
//将字节数组里面的内容存/写入缓存流
//参数1:待写入的数组
//参数2:起点
//参数3:长度
baos.write(b, 0, len);
}
String msg = new String(baos.toByteArray());
Log.e("MainActivityTAG", msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void myClick(View v) {
switch (v.getId()) {
// Android4.0 以后网络操作必须放在子线程中
case R.id.btn_post:
final String account = etAccount.getText().toString().trim();
final String password = etPassword.getText().toString().trim();
new Thread() {
@Override
public void run() {
super.run();
post(account, password);
}
}.start();
break;
}
}

控制台上面的数据如下,我们已经成功的登陆了。

android 生成url对象 安卓设置url_android网络操作_05

Android 中的网络操作(HttpURLConnection)相关教程