Retrofit2的简单封装

在练习做一个简单的天气app,网络请求用的是Retrofit2,本来只要请求一个城市的信息,现在需要请求多个,再直接使用Retrofit2就有点麻烦了,于是做了一下简单的封装,用的单例模式。


public class RetrofitFactory {

    public static final String BASE_URL = "http://apis.baidu.com/apistore/weatherservice/";
    private Retrofit retrofit;
    private static RetrofitFactory instance;

    private RetrofitFactory() {
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException
            {
                Request newRequest = chain.request().newBuilder().addHeader("apikey", "abcdefghijkl").build();
                return chain.proceed(newRequest);
            }
        }).build();//添加header部分

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

    }

    public static RetrofitFactory getInstance() {
        if (instance == null) {
            synchronized (RetrofitFactory.class) {
                if (instance == null) {
                    instance = new RetrofitFactory();
                }
            }
        }
        return instance;
    }

    public  RetrofitService1 getService() {
        RetrofitService1 service = retrofit.create(RetrofitService1.class);
        return service;
    }
}

使用Retrofit2要定义的接口RetrofitService

public interface RetrofitService {
    @GET("recentweathers")
    Call getWeather(@Query("cityname")String cityname);
}

使用时:

Call call = RetrofitFactory.getInstance().getService().getWeather("");
        call.enqueue(new Callback(){
            @Override
            public void onResponse(Call call, Response response){
                //请求成功处理数据

            }

            @Override
            public void onFailure(Call call, Throwable t){
                //进行异常情况处理
            }
        });

你可能感兴趣的:(Retrofit2的简单封装)