android:Retrofit2网络请求封装

发布时间 2023-04-26 15:32:37作者: cps666

原文地址 blog.csdn.net

  1. Retrofit使用
    =================================================================================

Retrofit是一个网络请求框架,先来说一下怎么使用

  • 网络权限(添加到AndroidManifest.xml)
<uses-permission android: />
  • gradle依赖(添加到build.gradle)
 1.      implementation("com.squareup.okhttp3:okhttp:4.9.2")
2.      implementation 'com.squareup.retrofit2:retrofit:2.9.0'
3.      implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
4.      implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
  • 定义接口,网络请求的方法


1.  public interface Request {

3.      @GET("/xx/xx")
4.      Call<ResponseBody> get();

6.  }


  • 实例化Retrofit
Retrofit retrofit = new Retrofit.Builder().baseUrl("BASE_URL").build();
  • 通过Retrofit实例创建接口服务对象
Request request = retrofit.create(Request.class);
  • 调用接口中的方法
Call<ResponseBody> call = request.get();
  • 执行异步请求(同步请求需要创建一个新的线程去执行)


1.  call.enqueue(new retrofit2.Callback<ResponseBody>() {
2.              @Override
3.              public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {

5.              }

7.              @Override
8.              public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {

10.              }
11.  });


  1. Retrofit封装
    =============

以上可以看出Retrofit是个好东西,可是用起来是比较麻烦的,所有在实际使用中对Retrofit进行一下小小的封装是很有必要的。

  • 定义接口(所有的请求参数都是以map的形式)
`

1.  public interface Request {

3.      /**
4.       * 不带参数的get请求
5.       * @param url
6.       * @return
7.       */
8.      @GET()
9.      Call<ResponseBody> get(@Url String url);

11.      /**
12.       * 带参数的get请求
13.       * @param url
14.       * @param map 参数默认是map
15.       * @return
16.       */
17.      @GET()
18.      Call<ResponseBody> get(@Url String url, @QueryMap Map<String,String> map);

20.      /**
21.       * 不带参数的post请求
22.       * @param url
23.       * @return
24.       */
25.      @POST()
26.      Call<ResponseBody> post(@Url String url);

28.      /**
29.       * 带参数的post请求
30.       * @param url
31.       * @param map
32.       * @return
33.       */
34.      @POST()
35.      @FormUrlEncoded
36.      Call<ResponseBody> post(@Url String url, @FieldMap Map<String,String> map);

39.  }

`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
  • 定义RetrofitManager,以单例模式获取Retrofit实例
`

1.  public enum RetrofitManager {

3.      /**
4.       * RetrofitManager的实例
5.       */
6.      INSTANCE;

8.      /**
9.       *
10.       * 后端接口的baseUrl,且只考虑一个url的情况(ip+端口,或者域名)
11.       */
12.      private static final String BASE_URL = " Your BASE_URL";

14.      private Retrofit retrofit;

16.      /**
17.       * 返回Retrofit实例,不添加转换器
18.       * @return
19.       */
20.      public Retrofit getRetrofit(){
21.          if(retrofit == null){
22.              retrofit = new Retrofit.Builder()
23.                      .baseUrl(BASE_URL)
24.                      .build();
25.          }
26.          return retrofit;
27.      }
28.  }

`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
  • 自定义的RetrofitCallback,在发送请求时,通过匿名对象作为参数获取后端的响应结果。
`

1.  public abstract class RetrofitCallback {

4.      /**
5.       * 开始执行的方法
6.       */
7.      public void onStart(){
8.          //开启loading
9.      }

11.      /**
12.       * 结束执行的方法
13.       */
14.      public void onCompleted(){
15.          //关闭loading
16.      }

18.      /**
19.       * 执行成功
20.       * @param resultJsonString  返回的json字符串
21.       */
22.      public abstract void onSuccess(String resultJsonString);

24.      /**
25.       * 失败
26.       * @param t 异常
27.       */
28.      public abstract void onError(Throwable t);

30.      /**
31.       * 提示:服务异常
32.       */
33.      public void serverErrMsg(){
34.          //xxx
35.      }

37.      /**
38.       * 提示:请求失败
39.       */
40.      public void reqErrMsg(){
41.          //xxx
42.      }

45.      /**
46.       * 提示:成功
47.       */
48.      public void okMsg(){
49.          //xxx
50.      }

52.  }

`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
  • 定义RetrofitUtil,封装get和post方法。将RetrofitCallback作为请求参数,在发送请求时重写onSuccess和onError方法,执行具体的操作。
`

1.  public class RetrofitUtil {

3.      private Retrofit(){}

5.      /**
6.       * 无参的get请求
7.       * @param url
8.       * @param callback
9.       */
10.      public static void get(String url, RetrofitCallback callback){
11.          sendRequest(getRequest().get(url),callback);
12.      }

14.      /**
15.       * 有参的get请求
16.       * @param url  请求的url
17.       * @param map  参数
18.       * @param callback  请求结束的回调
19.       */
20.      public static void get(String url, Map<String,String> map, RetrofitCallback callback){
21.          sendRequest(getRequest().get(url,map),callback);
22.      }

24.      /**
25.       * 无参的post请求
26.       * @param url
27.       * @param callback
28.       */
29.      public static void post(String url, RetrofitCallback callback){
30.          sendRequest(getRequest().post(url), callback);
31.      }

33.      /**
34.       * 有参的post请求
35.       * @param url
36.       * @param map
37.       * @param callback
38.       */
39.      public static void post(String url, Map<String,String> map, RetrofitCallback callback){
40.          sendRequest(getRequest().post(url,map), callback);
41.      }

44.      /**
45.       * 获取Request实例
46.       * @return
47.       */
48.      private static Request getRequest(){
49.          Retrofit retrofit = RetrofitManager.INSTANCE.getRetrofit();
50.          return retrofit.create(Request.class);
51.      }

53.      /**
54.       * 发送请求的共通方法,并对响应结果进行处理
55.       * @param call
56.       * @param callback 自定义的Callback
57.       */
58.      private void sendRequest(Call<ResponseBody> call,RetrofitCallback callback){

60.          //开启loading
61.          callback.onStart();
62.          //异步请求
63.          call.enqueue(new Callback<ResponseBody>() {
64.              @Override
65.              public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
66.                  //关闭loading
67.                  callback.onCompleted();
68.                  if(response.isSuccessful()){
69.                      //执行RetrofitCallback的onSuccess方法,获取响应结果的json字符串
70.                      try {
71.                          String result = response.body().string();
72.                          callback.onSuccess(result);
73.                          //响应成功
74.                          if(StringUtils.equals(result, Constant.SUCCESS)){
75.                              callback.okMsg();
76.                          }
77.                      } catch (IOException e) {
78.                          e.printStackTrace();
79.                      }
80.                  }else{
81.                      //服务异常
82.                      callback.serverErrMsg();
83.                  }
84.              }

86.              @Override
87.              public void onFailure(Call<ResponseBody> call, Throwable t) {
88.                  callback.onCompleted();
89.                  //请求失败
90.                  callback.onError(t);

92.                  callback.reqErrMsg();
93.                 }
94.              }
95.          });
96.      }
97.  }

`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
  1. RetrofitUtil使用
    =================

get无参请求



1.  RetrofitUtil.get("/xx/xx", new RetrofitCallback() {
2.      @Override
3.      public void onSuccess(String resultJsonString) {

5.      }

7.      @Override
8.      public void onError(Throwable t) {

10.      }
11.  });


get有参请求



1.  Map<String,String> map = new HashMap<>(16);
2.  map.put("key","value");
3.  //xxx
4.  RetrofitUtil.get("/xx/xx", map,new RetrofitCallback() {
5.      @Override
6.      public void onSuccess(String resultJsonString) {
7.          xxxx
8.      }

10.      @Override
11.      public void onError(Throwable t) {
12.          xxxx
13.      }
14.  });


post请求和get的使用方法相似

  1. 最后
    =====

本次只对get和post进行了封装,项目中只用到了这些就没有对文件上传下载以及别的请求方式进行封装。且没有添加转换器,可在RetrofitManager的getRetrofit()方法中自行添加。大概的封装思路就是这样的,可以自行发挥。

此文也只是在记录项目中对Retrofit的使用,对Retrofit的原理并没有较深的了解。

不足之处、欢迎留言。

感谢:对以下大佬的文章进行过参考,特此感谢

Android网络框架Retrofit2使用封装:Get/Post/文件上传/下载

Retrofit的封装