1、Retrofit简介
Retrofit无疑是当下最流行的Android网络请求框架了,是Square提供的开源产品。官方网站是这样介绍Retrofit的—-A type-safe HTTP client for Android and Java,为Android平台的应用提供一个类型安全的HTTP客户端。Retrofit 是一套注解形式的网络请求封装库,它的强大在于让代码结构更加清晰,它可以直接解析JSON数据变成JAVA对象,支持回调操作,处理不同的结果。
2、添加依赖:
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.0-RC1'
3、简单封装
public class ApiWrapper {
public static final String BASE_URL = "http://111.111.1.11/";
private Retrofit retrofit;
private static ApiWrapper instance;
private String token;
private ApiWrapper() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Content-Type", "charset=UTF-8")
.addHeader("Connection", "keep-alive").build();
return chain.proceed(request);
}
};
OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS).addInterceptor(logging).addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient).build();
}
public static ApiWrapper getInstance() {
if (instance == null) {
synchronized (ApiWrapper.class) {
if (instance == null) {
instance = new ApiWrapper();
}
}
}
return instance;
}
public <T> T create(Class<T> services) {
return retrofit.create(services);
}
}
单例模式构建的一个ApiWrapper,这样就不用每次请求网络数据的时候去构建一个retrofit
接口类
public class ApiService {
public static final String RES_GET_CITIES_LIST = "url/getCities";
public interface CityService {
@GET(RES_GET_CITIES_LIST)
Call<CityManager> getCity
(@QueryMap Map<String, String> queryMap);
}
}
使用的时候也很方便:
ApiService.CityService cityService = ApiWrapper.getInstance().create(ApiService.CityService.class);
Call<CityManager> call = cityService.getCity(queryMap);
call.enqueue(new Callback<CityManager>(){
@Override
public void onResponse(Call<CityManager> call, Response<CityManager> response){
//请求成功处理数据
}
@Override
public void onFailure(Call<CityManager> call, Throwable t){
//进行异常情况处理
}
});