在项目的开发当中,网络请求可谓是至关重要的一个环节,我们需要对于的请求方法[post,get,delete...]进行统一的封装,方便我们在项目中进行调用,而不至于在每一个需要进行网络请求的地方都进行一次重复的网络请求方法,这里我们就想到了一个很nice的框架---retrofit,Retrofit是一个用于安卓和java的http框架,通常我们会使用其进行网络的连接调用
首先需要添加gradle的引用
retrofitDeps = [
retrofit2 : "com.squareup.retrofit2:retrofit:2.9.0",
//日志的拦截器
logging : "com.squareup.okhttp3:logging-interceptor:3.14.9",
google_gson: "com.google.code.gson:gson:2.8.5"
]
接下来式封装一个全局的retrofit对象,方便我们对于后续的接口请求进行调用
public final class RetrofitHelper {
/**
* 全局的Retrofit对象,like Charset#bugLevel,HttpLoggingInterceptor#level,
* AsyncTask#mStatus,facebook->stetho->LogRedirector#sLogger,Timber->forestAsArray
* CopyOnWriteArrayList==
*/
public static volatile Retrofit DEFAULT;
private RetrofitHelper() {
throw new AssertionError("No instances.");
}
public static <T> T create(Class<T> service) {
//确保多线程的情况下retrofit不为空或者被修改了
Retrofit retrofit = DEFAULT;
if (retrofit == null) {
throw new IllegalStateException("DEFAULT == null");
}
return retrofit.create(service);
}
}
最主要的是我们需要对返回的方法进行统一的调用了
public abstract class AnimCallback<T> extends BodyCallback<T> {
private Dialog loadingPop;
private final Context context;
private String message;
public AnimCallback(Context context) {
this.context = context;
}
public AnimCallback(Context context, String message) {
this.context = context;
this.message = message;
}
@Override
public void onStart(Call<T> call) {
showLoading();
}
@NonNull
@Override
protected HttpError parseThrowable(Call<T> call, Throwable t) {
if (t instanceof JsonSyntaxException) {
return new HttpError("解析异常", -100, t);
}
return super.parseThrowable(call, t);
}
@Override
public void onCompleted(Call<T> call) {
hideLoading();
}
private void showLoading() {
if (loadingPop == null) {
loadingPop = new Dialog(context, R.style.NoTitleDialogStyle);
loadingPop.setContentView(R.layout.popup_loading);
loadingPop.setCanceledOnTouchOutside(false);
loadingPop.setCancelable(false);
}
loadingPop.show();
}
private void hideLoading() {
if (loadingPop != null) {
loadingPop.dismiss();
}
}
}
重中之重是我们需要对于retrofit的请求进行初始化
LogInterceptor logInterceptor = new LogInterceptor(message -> {
});
logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(logInterceptor)
.connectTimeout(13L, TimeUnit.SECONDS)
.readTimeout(13L, TimeUnit.SECONDS)
.build();
RetrofitHelper.DEFAULT = new Retrofit.Builder()
.baseUrl(Constants.Urls.BASE_URL)
.callFactory(new ReplaceUrlCallFactory(client) {
@Nullable
@Override
protected HttpUrl getNewUrl(String baseUrlName, Request request) {
//这里进行动态替换baseUrl
if (baseUrlName.equals("pic")) {
String oldUrl = request.url().toString();
String newUrl = oldUrl.replace(Constants.Urls.BASE_URL,
"http://www.baidu.com/");
return HttpUrl.get(newUrl);
}
return null;
}
})
.addCallAdapterFactory(CompletableCallAdapterFactory.INSTANCE)
.addConverterFactory(GsonConverterFactory.create())
.build();
最后不要忘记了添加权限哦,否则会无法连接到网络的
<uses-permission android:name="android.permission.INTERNET" />