retrofit2.0 封装
2019-01-03 本文已影响0人
Thor_果冻
/**
* 类描述:网络请求管理 <br/>
* 创建人:吴冬冬<br/>
* 创建时间:2017/8/4 15:58 <br/>
*/
public class HttpManger {
public static final int HTTP_MANGER_CIRCLE = 10010;
private static Context mContext;
private static HttpManger mHttpManger;
private static OkHttpClient.Builder okhttpBuilder;
private static Retrofit.Builder retrofitBuilder;
private static OkHttpClient okHttpClient;
private static Retrofit retrofit;
public static BaseApiService apiManager;
private final String baseUrl;
private boolean isShowLoading = false;
private int isShowLoadingType = HTTP_MANGER_CIRCLE;
private HttpManger(String baseUrl, BaseApiService apiManager, boolean isShowLoading, int isShowLoadingType){
this.baseUrl = baseUrl;
this.apiManager = apiManager;
this.isShowLoading = isShowLoading;
this.isShowLoadingType = isShowLoadingType;
}
public void executeGet(Context context, final String url, RetrofitCallback retrofitCallback) {
Call<ResponseBody> call = apiManager.executeGet(url);
if (isShowLoading == true) {
retrofitCallback.addShowLoading(context, isShowLoading, isShowLoadingType);
}
call.enqueue(retrofitCallback);
}
public void executeGet(Context context, final String url, @QueryMap(encoded = true) final Map<String, String> maps, RetrofitCallback retrofitCallback) {
Call<ResponseBody> call = apiManager.executeGet(url, maps);
if (isShowLoading == true) {
retrofitCallback.addShowLoading(context, isShowLoading, isShowLoadingType);
}
call.enqueue(retrofitCallback);
}
public void executePost(Context context, final String url, @FieldMap(encoded = true) final Map<String, String> maps, RetrofitCallback retrofitCallback) {
Call<ResponseBody> call = apiManager.executePost(url, maps);
if (isShowLoading == true) {
retrofitCallback.addShowLoading(context, isShowLoading, isShowLoadingType);
}
call.enqueue(retrofitCallback);
}
public static final class Builder {
private static final int DEFAULT_TIMEOUT = 15;
private Context context;
private String baseUrl;
private boolean isLog = false;
private Converter.Factory converterFactory;
private boolean isShowLoading = false;
private int isShowLoadingType = HTTP_MANGER_CIRCLE;
public Builder(Context context) {
okhttpBuilder = new OkHttpClient.Builder();
retrofitBuilder = new Retrofit.Builder();
if(context instanceof Activity) {
this.context = ((Activity) context).getApplicationContext();
} else {
this.context = context;
}
}
/**
* 添加默认地址
*/
public Builder baseUrl(String baseUrl) {
this.baseUrl = Utils.checkNotNull(baseUrl, "baseUrl == null");
return this;
}
/**
* 设置okhttpClient
*/
@NonNull
public Builder client(OkHttpClient client) {
retrofitBuilder.client(Utils.checkNotNull(client, "client == null"));
return this;
}
/**
* 设置连接时间
*/
public Builder connectTimeout(int timeout) {
return connectTimeout(timeout, TimeUnit.SECONDS);
}
public Builder connectTimeout(int timeout, TimeUnit unit) {
if (timeout != -1) {
okhttpBuilder.connectTimeout(timeout, unit);
} else {
okhttpBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
}
return this;
}
/**
* 设置写时间
*/
public Builder writeTimeout(int timeout) {
return writeTimeout(timeout, TimeUnit.SECONDS);
}
public Builder writeTimeout(int timeout, TimeUnit unit) {
if (timeout != -1) {
okhttpBuilder.writeTimeout(timeout, unit);
} else {
okhttpBuilder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
}
return this;
}
/**
* 设置读时间
*/
public Builder readTimeout(int timeout) {
return readTimeout(timeout, TimeUnit.SECONDS);
}
public Builder readTimeout(int timeout, TimeUnit unit) {
if (timeout != -1) {
okhttpBuilder.readTimeout(timeout, unit);
} else {
okhttpBuilder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
}
return this;
}
/**
* 设置是否显示网络连接log
*/
public Builder addLog(boolean isLog) {
this.isLog = isLog;
return this;
}
/**
* 是否显示加载框
*/
public Builder addShowLoading(boolean isShowLoading){
this.isShowLoading = isShowLoading;
return this;
}
/**
* 是否显示加载框
*/
public Builder addShowLoading(boolean isShowLoading, int type){
this.isShowLoading = isShowLoading;
this.isShowLoadingType = type;
return this;
}
/**
* 设置添加gson解析fastJson解析。。。
*/
public Builder addConverterFactory(Converter.Factory factory) {
this.converterFactory = factory;
return this;
}
public HttpManger build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
if (okhttpBuilder == null) {
throw new IllegalStateException("okhttpBuilder required.");
}
if (retrofitBuilder == null) {
throw new IllegalStateException("retrofitBuilder required.");
}
mContext = context;
//ConfigLoader.init(context);
retrofitBuilder.baseUrl(baseUrl);
//gson
/*if (converterFactory == null) {
converterFactory = GsonConverterFactory.create();
}*/
if (converterFactory != null) {
retrofitBuilder.addConverterFactory(converterFactory);
}
//rxjava
/*if (callAdapterFactory == null) {
callAdapterFactory = RxJavaCallAdapterFactory.create();
}
retrofitBuilder.addCallAdapterFactory(callAdapterFactory);*/
//LogWraper.setDebug(isLog && !BuildConfig.DEBUG);
if (isLog) {
okhttpBuilder.addNetworkInterceptor(
new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS));
okhttpBuilder.addNetworkInterceptor(
new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
}
okHttpClient = okhttpBuilder.build();
retrofitBuilder.client(okHttpClient);
retrofit = retrofitBuilder.build();
apiManager = retrofit.create(BaseApiService.class);
return new HttpManger(baseUrl, apiManager, isShowLoading, isShowLoadingType);
}
}
}
/**
* 类描述:retrofit接口服务<br/>
* 创建人:吴冬冬<br/>
* 创建时间:2017/8/4 14:51 <br/>
*/
public interface BaseApiService {
/**
* @Url 替换url
* @QueryMap 替换url中查询参数
* @Header 替换header
* @FieldMap 替换post请求body中参数
* @FormUrlEncoded post请求需要加的方法注解
* @POST() 标示该方法为post请求
* @GET() 标示该方法为get请求
*/
@GET()
Call<ResponseBody> executeGet(@Url String url);
//@GET("{path}")
//Call<ResponseBody> executeGet(@Path("path") String path, @QueryMap Map<String, String> datas);
//如果上面这种写法或出现URL异常
// http://api.myapi.com/http%3A%2F%2Fapi.mysite.com%2Fuser%2Flist
//@GET("{path}")
//Call<ResponseBody> executeGet(@Path(value = "path", encoded = true) String path, @QueryMap Map<String, String> datas);
@GET()
Call<ResponseBody> executeGet(@Url String url, @QueryMap Map<String, String> datas);
//@FormUrlEncoded//如果使用fileMap必须加上encoded注解
//@POST("{path}")
//Call<ResponseBody> postMethod(@Path(value = "path", encoded = true) String path, @FieldMap Map<String, String> dates);
@FormUrlEncoded//如果使用fileMap必须加上encoded注解
@POST()
Call<ResponseBody> executePost(@Url String url, @FieldMap Map<String, String> dates);
}
/**
* 类描述: <br/>
* 创建人:吴冬冬<br/>
* 创建时间:2017/8/4 18:26 <br/>
*/
public abstract class RetrofitCallback implements Callback {
private ProgressDialog mProgressDialog;
/**
* 成功中也会可能有错误信息,如账号错误之类的
*/
public abstract void onSuccess(String success);
public abstract void onError(String error);
public void addShowLoading(Context context, boolean isShowLoading, int isShowLoadingType){
if (isShowLoading) {
if (isShowLoadingType == HttpManger.HTTP_MANGER_CIRCLE) {//无限循环
mProgressDialog = new ProgressDialog(context);
mProgressDialog.setMessage(context.getString(R.string.net_loading));
} else {
//其他类型加载框
}
if (mProgressDialog != null) {
mProgressDialog.show();
}
}
}
@Override
public void onResponse(Call call, Response response) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
if (response.isSuccessful()) {
onSuccess(response.body().toString());
}
}
@Override
public void onFailure(Call call, Throwable t) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
if (t != null && t.getMessage() != null) {
onError(t.getMessage());
}
}
}
/**
* 类描述:工具类 <br/>
* 创建人:吴冬冬<br/>
* 创建时间:2017/8/4 17:20 <br/>
*/
public class Utils {
public static <T> T checkNotNull(T object, String message) {
if (object == null) {
throw new NullPointerException(message);
}
return object;
}
}