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<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){
                //進行異常情況處理
            }
        });
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,466評論 25 708
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,981評論 19 139
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,251評論 4 61
  • 這是你生命中最好的年紀,身體健康,親人安在,現世安穩。可惜你意識不到,因為一點小事,心情就一團糟。
    小爺power閱讀 262評論 0 0
  • 在docker中使用selenium做自動化測試,聽起來好有B格。筆者在學習的過程中也遇到了很多坑,本文zalen...
    cooling2016閱讀 1,334評論 5 8