大家好,又见面了,我是你们的朋友全栈君。
Android网络框架OKGo封装
本文讲述了Android网络框架OKGo封装,封装的框架适用于项目当中,适合新手操作,OKGO框架本身就以简单易上手而深受喜欢,而此文就是基于框架之上再次封装,废话不多说,直接开始吧!
首先在我们的build.gradle中导入我们引用的框架
代码语言:javascript复制dependencies {
...
implementation 'com.lzy.net:okgo:3.0.4'
implementation 'com.lzy.net:okserver:2.0.5'
...
}
下来就要在我们创建的Application文件中对OKGo进行相应的配置: 这里只进行简单的配置操作,如果想配置其他,可在网上查阅相关资料,在创建的Application文件的onCreate()方法实现初始化方法即可。
代码语言:javascript复制private void initOKGO() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
loggingInterceptor.setColorLevel(Level.INFO);
builder.addInterceptor(loggingInterceptor);
builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));
HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
OkGo.getInstance().init(this)
//设置OkHttpClient
.setOkHttpClient(builder.build())
//全局统一缓存模式
.setCacheMode(CacheMode.NO_CACHE)
//全局统一缓存时间
.setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
//全局统一超时重连次数
.setRetryCount(3);
}
有时候我们的需求是在网络请求中,我们需要给用户展示一个loading等待框,提示用户正在进行网络请求操作,下来我们就展示等待提示的代码: DialogJsonCallback
代码语言:javascript复制public class DialogJsonCallback extends StringCallback {
private AlertDialog alertDialog;
private Activity activity;
public DialogJsonCallback() {
}
public DialogJsonCallback(Activity activity) {
super();
initDialog(activity);
}
private void initDialog(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.matching_dialog);
this.activity = activity;
alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
activity.setFinishOnTouchOutside(false);
View view = LayoutInflater.from(activity).inflate(R.layout.matching_dialog_layout, null);
alertDialog.setView(view);
}
@Override
public void onStart(Request<String, ? extends Request> request) {
super.onStart(request);
if (alertDialog != null && !alertDialog.isShowing()) {
alertDialog.show();
alertDialog.getWindow().setContentView(R.layout.matching_dialog_layout);
}
}
@Override
public void onFinish() {
super.onFinish();
if (activity != null) {
if (!activity.isDestroyed()) {
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
}
}
}
@Override
public void onSuccess(Response<String> response) {
}
}
其中的样式代码为: R.style.matching_dialog
代码语言:javascript复制<style name="matching_dialog" parent="@android:style/Theme.Holo.Dialog">
<!-- 是否有边框 -->
<item name="android:windowFrame">@null</item> <!--是否在悬浮Activity之上 -->
<item name="android:windowIsFloating">true</item> <!--标题 -->
<item name="android:windowNoTitle">true</item> <!--阴影 -->
<item name="android:windowIsTranslucent">true</item> <!--透明背景-->
<item name="android:background">@android:color/transparent</item> <!--窗口背景透明-->
<item name="android:windowBackground">@android:color/transparent</item> <!--弹窗背景是否变暗-->
<item name="android:backgroundDimEnabled">false</item>
</style>
用到的布局文件为: 布局文件为一个简单的.gif图提示用户 R.layout.matching_dialog_layout
代码语言:javascript复制<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/logout_bg_round">
<pl.droidsonroids.gif.GifImageView
android:id="@ id/gif_icon_matching"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@mipmap/icon_matching"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:text="@string/in_the_match"
android:textColor="@color/black"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/gif_icon_matching"/>
</androidx.constraintlayout.widget.ConstraintLayout>
下来就是对OKGO框架进行网络请求的封装:
首先我们先定义网络请求回传的接口,当网络请求成功或失败时,对返回数据进行回调:
HttpRquestInter
代码语言:javascript复制public interface HttpRequestInter<T> {
void onError(String des);
void onResponse(T responseObj);
}
下来我们封装OKGo的网络请求操作,包括get,post,以及文件上传:
代码语言:javascript复制public class HttpRequest {
/** * OKGo Get请求 * @param url * @param params * @param classz * @param requestInter * @param <T> */
public static <T> void getRequets(Activity activity, String url, Map<String, String> params, final Class classz, final HttpRquestInter<T> requestInter) {
OkGo.<T>get(url)
.headers("公共请求头部", " ")
.headers("公共请求头部", " ")
.params(params)
.execute((Callback<T>) new DialogJsonCallback(activity) {
@Override
public void onError(Response<String> response) {
try {
requestInter.onError(response.body());
} catch (Exception e1) {
e1.printStackTrace();
}
}
@Override
public void onSuccess(Response<String> response) {
//请求返回数据可根据需求更改判断
requestInter.onResponse((T) new Gson().fromJson(response.body(), classz));
}
});
}
/** * OKGo post请求 * @param url * @param params * @param classz * @param requestInter * @param <T> */
public static <T> void postRequest(Activity activity, String url, Map<String, String> params, final Class classz, final HttpRquestInter<T> requestInter) {
OkGo.<T>post(url)
.headers("公共请求头部", "")
.headers("公共请求头部", "")
.params(params)
.execute((Callback<T>) new DialogJsonCallback(activity) {
@Override
public void onError(Response<String> response) {
try {
requestInter.onError(response.body());
} catch (Exception e1) {
e1.printStackTrace();
}
}
@Override
public void onSuccess(Response<String> response) {
//请求返回数据可根据需求更改判断
requestInter.onResponse((T) new Gson().fromJson(response.body(), classz));
}
});
}
/** * OKGo 文件上传 * @param url * @param files * @param classz * @param requestInter * @param <T> */
public static <T> void fileUpload(Activity activity, String url, String fileKey, File files, String fileName, final Class classz, final HttpRquestInter<T> requestInter) {
HttpParams httpParams = new HttpParams();
httpParams.put(fileKey, files, fileName);
OkGo.<T>post(url)
.headers("公共请求头部", "")
.headers("公共请求头部", "")
.params(httpParams)
.isMultipart(true)
.execute((Callback<T>) new DialogJsonCallback(activity) {
@Override
public void onError(Response<String> response) {
try {
requestInter.onError(response.body());
} catch (Exception e1) {
e1.printStackTrace();
}
}
@Override
public void onSuccess(Response<String> response) {
//请求返回数据可根据需求更改判断
requestInter.onResponse((T) new Gson().fromJson(response.body(), classz));
}
});
}
}
我们可以创建一个公共的类来整理我们的网络请求参数
代码语言:javascript复制public class RequestBodyManager {
//登录
public static Map<String, String> buildLoginPostParam(String userName, String passWord) {
Map<String, String> defaults = new HashMap<>();
defaults.put("userName", userName;
defaults.put("passWord", passWord);
return defaults;
}
}
最后我们演示一下模拟登录的代码:
代码语言:javascript复制public void loginPost(String userName, String passWord) {
Map<String, String> loginMap = RequestBodyManager.buildLoginPostParam(userName, passWord);
HttpRequest.postRequest(getView(), Constants.LOGIN, loginMap, LoginResponse.class, new HttpRquestInter<LoginResponse>() {
@Override
public void onError(String des) {
getView().loginFailure(des);
}
@Override
public void onResponse(LoginResponse responseObj) {
getView().loginSuccess(responseObj);
}
});
}
其中的getView()方法就是获取当前界面的Context,可以参考我之前的封装MVP代码。 最后把LoginResponse.class的代码也贴出来,可以根据这个更改。
LoginResponse
代码语言:javascript复制public class LoginResponse extends BaseModel<LoginInfo> {
}
只是简单的这一行代码,LoginInfo根据自己项目需求更改。
其中Get和Post的代码大概一致,下来讲述一下文件上传:
代码语言:javascript复制public void uploadFile(String fileKey, File file, String fileName) {
HttpRequest.fileUpload(getView(), Constants.CHANGE_PHOTO, fileKey, file, fileName, UploadResponse.class, new HttpRquestInter<UploadResponse>() {
@Override
public void onError(String des) {
getView().uploadPhotoFail(des);
}
@Override
public void onResponse(UploadResponse responseObj) {
if (responseObj.status) {
getView().uploadPhotoSuccess(responseObj);
} else {
getView().uploadPhotoFail(responseObj.errors);
}
}
});
}
以上就是封装OKGO的全部内容,如有不足之处,还请各位包涵!
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/128656.html原文链接:https://javaforall.cn