本文共 2678 字,大约阅读时间需要 8 分钟。
在项目中添加Retrofit相关的依赖方丈,确保开发环境的正确配置。本文采用Retrofit2.4.0版本,并结合RXJava2进行JSON数据处理。以下是完整的Gradle配置:
// RX Java 相关依赖compile 'io.reactivex.rxjava2:rxandroid:2.0.2'compile 'io.reactivex.rxjava2:rxjava:2.1.12'// Retrofit相关配置compile 'com.squareup.retrofit2:retrofit:2.4.0'compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'// OK Http 相关日志拦截compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
接下来,创建包含HTTP方法定义的接口类,明确网络请求的URL路径和请求类型。大多数情况下,我们使用@GET注解来定义GET请求。以下是一个典型的示例接口:
public interface WalletService { // @GET("/path/to/api") void getData(Call call); @GET("/tools/mockapi/3191/favourable") Call getFavourable();} 在主活动中初始化Retrofit,设置基础URL和自定义JSON转换器。下面是一个完整的创建请求示例:
Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://www.wanandroid.com") .addConverterFactory(new Converter.Factory() { @Override public Converter responseBodyConverter( Type type, Annotation[] annotations, Retrofit retrofit) { return new Converter () { @Override public String convert(ResponseBody value) throws IOException { return value.string(); } }; } }) .build();WalletService service = retrofit.create(WalletService.class);Call favourable = service.getFavourable();favoured.enqueue(new Callback () { @Override public void onResponse(Call call, Response response) { String message = response.body(); Log.e("打印返回的json数据", message); } @Override public void onFailure(Call call, Throwable t) { // 处理请求失败的情况 Log.e("请求失败", t.toString()); }}); 根据上述配置,实际发出的请求地址为:
http://www.wanandroid.com/tools/mockapi/3191/favourable
通过Retrofit的响应体转换器,可以直接将ResponseBody转化为String,方便日志打印和数据处理。日志打印示例如下:
String message = response.body();Log.e("打印返回的json数据", message); 在onFailure方法中,可以添加请求失败的处理逻辑,例如错误日志记录和重试机制等:
@Overridepublic void onFailure(Callcall, Throwable t) { // 描述请求失败原因 Log.e("请求失败", t.toString()); // 例如,可以将错误信息传递到主线程 runOnUiThread(() -> { Toast.makeText(context, "请求失败", Toast.LENGTH_LONG).show(); });}
需要注意的是,在实际开发中,网络请求的成功率和稳定性至关重要,因此可以考虑添加请求重试库或其他异常处理机制。
转载地址:http://srmnz.baihongyu.com/