Retrofit简单封装

我们知道在比较流行的网络框架里,有okhttp,retrofit,volley,而okhttp只支持 get 和post,而retrofit支持 get,put,post,header,等等 在开发中我对retrofit简单封装了一下。

1.导入依赖:

compile 'com.squareup.retrofit2:retrofit:2.4.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

2.创建ApiService:

@GET("query")
Call<TopicBean> getTopicList(@Query("app") String app, @Query("action") String action, @Query("shuidishichuan")
        String shuidishichuan, @Query("page") int page);

创建BaseModel:

public class BaseModel<T> {
    private long code ;//请求返回码
    private String msg;// 请求返回信息
    private int cost;
    private String timestamp;
    private T data;//请求返回的body

    public long getCode() {
        return code;
    }

    public void setCode(long code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
RetrofitUtils

public class RetrofitUtils {
    private Retrofit retrofit;
    private static ApiService apiService;
    public Handler mHandler = new Handler(Looper.getMainLooper());
    private static final class Holder{
        private static final RetrofitUtils INSTANCE =new RetrofitUtils();
    }
    public void initRxRetrofit(){
        OkHttpClient client =new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10,TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
        retrofit =new Retrofit.Builder()
                .baseUrl("http://hz.webdev.com/shuidi/api/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        apiService=retrofit.create(ApiService.class);
    }

    public static RetrofitUtils getInstance(){
        return Holder.INSTANCE;
    }
    public static ApiService Api(){
        if (apiService == null)
            throw new IllegalStateException("需要APPLICATION种初始化");
        return apiService;
    }

    public <T> void requestData(Call<T> call, final WaterDropInterdace<T> waterDropInterdace) {
        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(final Call<T> call, final Response<T> response) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        waterDropInterdace.onSuccess(response.body(),response.message(),response.code());
                    }
                });
            }

            @Override
            public void onFailure(final Call<T> call, final Throwable t) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        waterDropInterdace.onFailure(call,t);
                    }
                });
            }
        });
    }


 
 


定义接口

public interface WaterDropInterdace<T> {

    void onSuccess(T t, String msg, long code);

    void onFailure(Call call, Throwable throwable);

}

Callback回调

public class WaterDropCallback<T> implements Callback<T> {

    @Override
    public void onResponse(Call<T> call, Response<T> response) {

    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {

    }
}

public class WaterDropImpl {
    //    话题
    public void getTopicList(WaterDropInterdace<TopicBean> waterDropCallback) {
        Call<TopicBean> topicList = RetrofitUtils.Api().getTopicList("HotEvent", "loadEventList", "2", 1);
        RetrofitUtils.getInstance().requestData(topicList, waterDropCallback);

}

}

在Fragmenrt里使用

protected void initData() {

    new WaterDropImpl().getTopicList(new WaterDropInterdace<TopicBean>() {
        @Override
        public void onSuccess(TopicBean topicBean, String msg, long code) {
            if (code == 200) {
                list.clear();
                list.addAll(topicBean.getData().getList());
                adapter.notifyDataSetChanged();
            }
            refreshLayout.setRefreshing(false);
        }

        @Override
        public void onFailure(retrofit2.Call call, Throwable throwable) {
            Log.e("shuidi", throwable.getMessage());
            Toast.makeText(getContext(), "失败", Toast.LENGTH_SHORT).show();
        }
    });

}

最后我们开一下效果


猜你喜欢

转载自blog.csdn.net/qq_38875767/article/details/80985033