Retrofit
1、Retrofit 概述
- Retrofit 是一个网络请求库,专门用于发送 HTTP 请求和处理 HTTP 响应
2、Retrofit 引入
- 在 AndroidManifest.xml 文件中添加相关权限,如果是 Android 6.0(API 级别 23)或之后,需要在运行时请求
<uses-permission android:name="android.permission.INTERNET" />
- 在模块级
build.gradle
中引入相关依赖
implementation 'com.squareup.okhttp3:logging-interceptor:3.8.1'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
implementation 'io.reactivex:rxandroid:1.2.0'
3、Retrofit 使用步骤
-
创建接口:创建一个接口,并定义具体的请求方法,使用 Retrofit 提供的注解来描述 HTTP 请求
-
配置 Retrofit:使用
Retrofit.Builder
构建出一个 Retrofit 实例对象 -
创建接口代理对象:通过 Retrofit 实例对象创建接口的代理对象
-
发送并处理请求:调用接口方法发送网络请求,通过回调处理请求结果
一、Retrofit GET 带参请求编码(2 种带参方式)
Server
- MyTestController.java
@RestController
@RequestMapping("/test")
@CrossOrigin
public class TestController {
@GetMapping("/testGetCarryData")
public String testGetCarryData(@RequestParam("str") String str) {
return "testGetCarryData " + str;
}
}
1、GET 请求(带参方式 1)
(1)Client Api
- ApiService.java
@GET("/test/testGetCarryData")
Call<String> testGetCarryData(@Query("str") String str);
(2)Client Test
- MainActivity.java
apiService.testGetCarryData("12345").enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
String result = response.body();
Log.i(TAG, "------------------------------ 请求成功,结果为:" + result);
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.i(TAG, "------------------------------ 请求失败:" + t.getMessage());
}
});
- 输出结果
D/OkHttp: --> GET http://192.168.0.10:9999/test/testGetCarryData?str=12345 http/1.1
D/OkHttp: --> END GET
D/OkHttp: <-- 200 http://192.168.0.10:9999/test/testGetCarryData?str=12345 (98ms)
D/OkHttp: Vary: Origin
D/OkHttp: Vary: Access-Control-Request-Method
D/OkHttp: Vary: Access-Control-Request-Headers
D/OkHttp: Content-Type: text/plain;charset=UTF-8
D/OkHttp: Content-Length: 22
D/OkHttp: Date: Sun, 29 Sep 2024 13:38:41 GMT
D/OkHttp: Keep-Alive: timeout=60
D/OkHttp: Connection: keep-alive
D/OkHttp: testGetCarryData 12345
D/OkHttp: <-- END HTTP (22-byte body)
I/MainActivity: ------------------------------ 请求成功,结果为:testGetCarryData 12345
2、GET 请求(带参方式 2)
(1)Client Api
- ApiService.java
@GET("/test/testGetCarryData")
Call<String> testGetCarryData2(@QueryMap Map<String, String> map);
(2)Client Test
- MainActivity.java
Map<String, String> map = new HashMap<>();
map.put("str", "12345");
apiService.testGetCarryData2(map).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
String result = response.body();
Log.i(TAG, "------------------------------ 请求成功,结果为:" + result);
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.i(TAG, "------------------------------ 请求失败:" + t.getMessage());
}
});
- 输出结果
D/OkHttp: --> GET http://192.168.0.10:9999/test/testGetCarryData?str=12345 http/1.1
D/OkHttp: --> END GET
D/OkHttp: <-- 200 http://192.168.0.10:9999/test/testGetCarryData?str=12345 (237ms)
D/OkHttp: Vary: Origin
D/OkHttp: Vary: Access-Control-Request-Method
D/OkHttp: Vary: Access-Control-Request-Headers
D/OkHttp: Content-Type: text/plain;charset=UTF-8
D/OkHttp: Content-Length: 22
D/OkHttp: Date: Mon, 30 Sep 2024 09:27:30 GMT
D/OkHttp: Keep-Alive: timeout=60
D/OkHttp: Connection: keep-alive
D/OkHttp: testGetCarryData 12345
D/OkHttp: <-- END HTTP (22-byte body)
I/MainActivity: ------------------------------ 请求成功,结果为:testGetCarryData 12345
二、Retrofit POST 表单请求编码(2 种带参方式)
Entity
- User.java
public class User {
private int id;
private String name;
private int age;
public User() {
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
Server
- MyTestController.java
@RestController
@RequestMapping("/test")
@CrossOrigin
public class TestController {
@PostMapping("/testFormData")
public User testFormData(@RequestParam Integer id) {
HashMap<Integer, User> userMap = new HashMap<>();
userMap.put(1, new User(1, "jack", 10));
userMap.put(2, new User(2, "tom", 20));
userMap.put(3, new User(3, "smith", 30));
return userMap.get(id);
}
}
1、POST 请求(带参方式 1)
(1)Client Api
- ApiService.java
@POST("/test/testFormData")
@FormUrlEncoded
Call<User> testFormData(@Field("id") int id);
(2)Client Test
- MainActivity.java
apiService.testFormData(1).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User result = response.body();
Log.i(TAG, "------------------------------ 请求成功,结果为:" + result);
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Log.i(TAG, "------------------------------ 请求失败:" + t.getMessage());
}
});
- 输出结果
D/OkHttp: --> POST http://192.168.0.10:9999/test/testFormData http/1.1
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 4
D/OkHttp: id=1
D/OkHttp: --> END POST (4-byte body)
D/OkHttp: <-- 200 http://192.168.0.10:9999/test/testFormData (134ms)
D/OkHttp: Vary: Origin
D/OkHttp: Vary: Access-Control-Request-Method
D/OkHttp: Vary: Access-Control-Request-Headers
D/OkHttp: Content-Type: application/json
D/OkHttp: Transfer-Encoding: chunked
D/OkHttp: Date: Thu, 03 Oct 2024 07:30:45 GMT
D/OkHttp: Keep-Alive: timeout=60
D/OkHttp: Connection: keep-alive
D/OkHttp: {"id":1,"name":"jack","age":10}
D/OkHttp: <-- END HTTP (31-byte body)
I/MainActivity: ------------------------------ 请求成功,结果为:User{id=1, name='jack', age=10}
2、POST 请求(带参方式 2)
(1)Client Api
- ApiService.java
@POST("/test/testFormData")
@FormUrlEncoded
Call<User> testFormData2(@FieldMap Map<String, String> map);
(2)Client Test
- MainActivity.java
Map<String, String> map = new HashMap<>();
map.put("id", "1");
apiService.testFormData2(map).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User result = response.body();
Log.i(TAG, "------------------------------ 请求成功,结果为:" + result);
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Log.i(TAG, "------------------------------ 请求失败:" + t.getMessage());
}
});
- 输出结果
D/OkHttp: --> POST http://192.168.3.8:9999/test/testFormData http/1.1
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 4
D/OkHttp: id=1
D/OkHttp: --> END POST (4-byte body)
D/OkHttp: <-- 200 http://192.168.0.10:9999/test/testFormData (146ms)
D/OkHttp: Vary: Origin
D/OkHttp: Vary: Access-Control-Request-Method
D/OkHttp: Vary: Access-Control-Request-Headers
D/OkHttp: Content-Type: application/json
D/OkHttp: Transfer-Encoding: chunked
D/OkHttp: Date: Thu, 03 Oct 2024 07:34:53 GMT
D/OkHttp: Keep-Alive: timeout=60
D/OkHttp: Connection: keep-alive
D/OkHttp: {"id":1,"name":"jack","age":10}
D/OkHttp: <-- END HTTP (31-byte body)
I/MainActivity: ------------------------------ 请求成功,结果为:User{id=1, name='jack', age=10}