在練習做一個簡單的天氣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){
//進行異常情況處理
}
});