安卓系统中如何使用网络请求库
56.04
注意事项
网络请求不能放到主线程中,要启动一个子线程运行
在清单文件中,赋予app网络权限
在包名下面加上这段内容
<uses-permission android:name="android.permission.INTERNET"/>
在module的gradle文件添加依赖
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.20'
操作方法如下图
GET 构建网络请求(同步写法)
private final OkHttpClient client = new OkHttpClient(); //新建一个okhttp的客户端
void OkHttpDemo(){
Request request = new Request.Builder().url("https://reqres.in/api/users?page=2").build(); //构建一个request请求
new Thread(new Runnable() { // 启动一个子线程
@Override
public void run() {
try {
Response response = client.newCall(request).execute(); // 发送requet 请求
Log.d(TAG, "OkHttpDemo: "+ response.body().string()); // 得到响应信息
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
GET 构建网络请求(推荐异步写法)
private final OkHttpClient client = new OkHttpClient(); //新建一个okhttp的客户端
void OkHttpAsync(){
Request request = new Request.Builder().url("https://reqres.in/api/users?page=2").build(); //构建一个request请求
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
// 请求失败走这里
Log.d(TAG, "onFailure: 请求失败");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
// 请求成功走这里
Log.d(TAG, "onResponse: "+ response.body().string());
}
});
}
GET URL参数构建
void okHttpBuilder(){
// 构建url
HttpUrl.Builder builder = HttpUrl.parse("https://reqres.in/api/users").newBuilder();
builder.addQueryParameter("page","2");
String url = builder.build().toString();
Log.d(TAG, "okHttpBuilder: " + url);
}
POST 请求
请求目标示例
url :https://reqres.in/api/users
要发送的数据
{
"name": "morpheus",
"job": "leader"
}
构建请求demo
private final OkHttpClient client = new OkHttpClient(); //新建一个okhttp的客户端
void okHttpPost(){
RequestBody body = new FormBody.Builder()
.add("name","morpheus")
.add("job","leader")
.build();
Request request = new Request.Builder().url("https://reqres.in/api/users").post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.d(TAG, "onFailure: 请求失败");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
Log.d(TAG, "onResponse: "+ response.body().string());
}
});
}