Retrofit 联网工具类 的简单封装

导入依赖

 implementation 'com.squareup.retrofit2:retrofit:2.4.0'

网络权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

首先新建一个接口 我们叫他BaseService

public interface BaseService {
  //get方法
@GET 
Call<ResponseBody> get(@Url String url, @QueryMap Map<String,String> map);


//post方法
@POST
Call<ResponseBody> post(@Url String url, @QueryMap Map<String,String> map);
}

新建一个工具类

 public class RetrofitUtils {
 private Retrofit retrofit;

 //单例模式
 private RetrofitUtils() {
 }
 private static RetrofitUtils retrofitUtils;

 public static RetrofitUtils getRetrofitUtils() {
     if (retrofitUtils == null) {
         retrofitUtils = new RetrofitUtils();
     }
     return retrofitUtils;
 }

 //初始化方法.
 //               接口的域名写在这里
 //  比如 baseUrl("http://www.zhaoapi.cn/") //比如 baseUrl("https://code.aliyun.com/")
 public void init() {
     retrofit = new Retrofit.Builder()
             .baseUrl("https://code.aliyun.com/")
             .build();
 }
 //get请求
 public RetrofitUtils get(String url, Map<String, String> map) {
     if (map == null) {
         map = new HashMap<>();
     }
     retrofit.create(BaseService.class).get(url, map).enqueue(new Callback<ResponseBody>() {
         @Override
         public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
             try {
                 listener.success(response.body().string());
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }

         @Override
         public void onFailure(Call<ResponseBody> call, Throwable t) {
             listener.fail();
         }
     });
     return this;
 }

 //get请求
 public RetrofitUtils post(String url, Map<String, String> map) {
     retrofit.create(BaseService.class).post(url, map).enqueue(new Callback<ResponseBody>() {

         @Override
         public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
             try {
                 listener.success(response.body().string());
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }

         @Override
         public void onFailure(Call<ResponseBody> call, Throwable t) {
             listener.fail();
         }
     });
     return this;
 }

 private HttpListener listener;

 public void result(HttpListener listener) {
     this.listener = listener;
 }

 public interface HttpListener {
     void success(String data);
     void fail();
 }
 }

猜你喜欢

转载自blog.csdn.net/qq_43143981/article/details/83718757