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 实例对象创建接口的代理对象
-
发送并处理请求:调用接口方法发送网络请求,通过回调处理请求结果
一、404 请求
1、Client Api
- ApiService.java
@GET("test/testGet12345")
Call<String> test404();
2、Client Test
- MainActivity.java
// 日志拦截器
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
okHttpClientBuilder.addInterceptor(httpLoggingInterceptor);
OkHttpClient okHttpClient = okHttpClientBuilder.build();
// 构建 Retrofit 对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://172.31.8.3:9999")
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create()) // 解析实体类
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 结合 RxJava
.build();
ApiService apiService = retrofit.create(ApiService.class);
apiService.test404().enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.code() == 200) {
String result = response.body();
Log.i(TAG, "------------------------------ 请求成功,结果为:" + result);
return;
}
if (response.code() == 404) {
Log.i(TAG, "------------------------------ 请求 404");
return;
}
Log.i(TAG, "------------------------------ 请求失败");
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.i(TAG, "------------------------------ 请求失败:" + t.getMessage());
Log.i(TAG, "------------------------------ " + t.getClass().getName());
}
});
- 输出结果
D/OkHttp: --> GET http://192.168.0.10:9999/test/testGet12345 http/1.1
D/OkHttp: --> END GET
D/OkHttp: <-- 404 http://192.168.0.10:9999/test/testGet12345 (101ms)
D/OkHttp: Content-Type: application/json
D/OkHttp: Transfer-Encoding: chunked
D/OkHttp: Date: Wed, 16 Oct 2024 13:01:13 GMT
D/OkHttp: Keep-Alive: timeout=60
D/OkHttp: Connection: keep-alive
D/OkHttp: {"timestamp":"2024-10-16T13:01:13.422+00:00","status":404,"error":"Not Found","path":"/test/testGet12345"}
D/OkHttp: <-- END HTTP (106-byte body)
I/MainActivity: ------------------------------ 请求 404
二、超时请求
1、Server
- TestController.java
@RestController
@RequestMapping("/test")
@CrossOrigin
public class TestController {
@GetMapping("/testTimeout")
public String testTimeout() {
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "testTimeout Hello World";
}
}
2、Client Api
- ApiService.java
@GET("/test/testTimeout")
Call<String> testTimeout();
3、Client Test
- MainActivity.java
// 日志拦截器
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
okHttpClientBuilder.addInterceptor(httpLoggingInterceptor);
okHttpClientBuilder.connectTimeout(10, TimeUnit.SECONDS); // 连接超时
okHttpClientBuilder.readTimeout(10, TimeUnit.SECONDS); // 读取超时
okHttpClientBuilder.writeTimeout(10, TimeUnit.SECONDS); // 写入超时
OkHttpClient okHttpClient = okHttpClientBuilder.build();
// 构建 Retrofit 对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://172.31.8.3:9999")
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create()) // 解析实体类
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 结合 RxJava
.build();
apiService = retrofit.create(ApiService.class);
apiService.testTimeout().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());
Log.i(TAG, "------------------------------ " + t.getClass().getName());
}
});
- 输出结果
D/OkHttp: --> GET http://192.168.0.10:9999/test/testTimeout http/1.1
D/OkHttp: --> END GET
D/OkHttp: <-- HTTP FAILED: java.net.SocketTimeoutException: timeout
I/Main2Activity: ------------------------------ 请求失败:timeout
I/Main2Activity: ------------------------------ java.net.SocketTimeoutException
三、连接失败请求(错误地址)
1、Client Api
- ApiService.java
@GET("/test/testGet")
Call<String> testFailedToConnect();
2、Client Test
- MainActivity.java
// 日志拦截器
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
okHttpClientBuilder.addInterceptor(httpLoggingInterceptor);
OkHttpClient okHttpClient = okHttpClientBuilder.build();
// 构建 Retrofit 对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.0.11:9999")
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create()) // 解析实体类
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 结合 RxJava
.build();
ApiService apiService = retrofit.create(ApiService.class);
apiService.testFailedToConnect().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());
Log.i(TAG, "------------------------------ " + t.getClass().getName());
}
});
- 输出结果
D/OkHttp: --> GET http://192.168.0.11:9999/test/testGet http/1.1
D/OkHttp: --> END GET
标签:请求,------------------------------,create,404,okHttpClientBuilder,new,Retrofit
From: https://blog.csdn.net/weixin_52173250/article/details/142992074