本篇学习 Android 网络请求中最常用的 okHttp
OkHttp 是由 Square 公司贡献的轻量级网络请求框架。
GIthub 地址 :OkHttp
下面开始学习 OkHttp 的使用
准备工作
// okHttp 3.14
implementation 'com.squareup.okhttp3:okhttp:3.14.9'
添加权限
<uses-permission android: />
下面我们就可以正式开始了
关于 OkHttp 的请求方式有同步和异步两种,下面分别学习
get 和 post 都有同步和异步两种方式
同步
-
get 的同步
get 的同步请求,同步请求在子线程中进行,更新 UI 要在 UI 线程中操作。
OkHttpClient okHttpClient = new OkHttpClient();
// 参数可以在后面拼接
Request request = new Request.Builder().url(BASE_URL).build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
Log.i(TAG, "getDataSync: " + response.body().string());
handler.post(new Runnable() {
@Override
public void run() {
// 更新UI
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
通过 response 的 isSuccessful 方法判断请求,在成功后就可以进行处理了。如果对 UI 进行操作需要在主线程处理。
-
post 的同步
post 的同步请求只要在 get 的基础上,在 Request 的实例化后面拼接上 post() 方法就可以了。
下面是异步请求。
异步
异步请求的回调是在子线程中,更新 UI 需要在主线程操作。
- get 的异步
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(BASE_URL).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// Failure
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.i(TAG, "onResponse: " + response.body().string());
// 更新UI
}
}
});
Ps:异步请求的 enqueue() 方法会自动将请求部分放入工作线程处理。回调方法是在工作线程中的。
- post 的异步
post 的异步和 get 的异步基本相同。和上面同步一样,只要在 Request 构建是调用 post 就可以了。
OkHttpClient client = new OkHttpClient();
// 表单请求体
FormBody.Builder builder = new FormBody.Builder();
builder.add("args1", "values1");
Request post = new Request.Builder().url(BASE_URL).post(builder.build()).build();
client.newCall(post).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// Failure
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
response.body().string();
// TODO
}
}
});
值得注意的地方是在调用 post 方法时,需要传入请求体参数,一个 RequestBody 类型的参数。这个参数可以分为四种情况。
- RequestBody 类型参数
- FormBody 对象
该对象用来传递以键值对形式的参数。上面的 post 异步就是通过该对象。 - RequestBody 对象
该对象用来传递 JSON 或者 File
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String jsonString = "{"name":"Alex","sex":"Male"}";
// 在create方法的参数中可以添加File或者JSON
RequestBody requestBody = RequestBody.create(JSON, jsonString);
- MultipartBody 对象
该对象可以传递复合类型的参数。
MultipartBody multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("name", "Alex")
.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("file/*"), file))
.build();
- 自定义 RequestBody 对象
我们可以通过继承 RequestBody 来实现流的上传
以上就是 OkHttp 的使用。
参考
OkHttp 的基本使用