美文网首页
Retrofit2的简单封装

Retrofit2的简单封装

作者: chenmingzhi | 来源:发表于2016-09-27 23:07 被阅读0次

    在练习做一个简单的天气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<WeatherBean> getWeather(@Query("cityname")String cityname);
    }
    

    使用时:

    Call<WeatherBean> call = RetrofitFactory.getInstance().getService().getWeather("");
            call.enqueue(new Callback<WeatherBean>(){
                @Override
                public void onResponse(Call<WeatherBean> call, Response<WeatherBean> response){
                    //请求成功处理数据
    
                }
    
                @Override
                public void onFailure(Call<WeatherBean> call, Throwable t){
                    //进行异常情况处理
                }
            });
    

    相关文章

      网友评论

          本文标题:Retrofit2的简单封装

          本文链接:https://www.haomeiwen.com/subject/pilhyttx.html