背景
封装的网络库基于okhttp3+retrofit2+rxandroid+rxjava。目的是单独封装处理网络请求,可供项目中多个module使用,所以Demo中代码模块拆的比较细。包含hsjokhttp(网络库封装)、hsjlogger(日志打印)、bean(对象模块),只需要关注hsjokhttp(网络库封装) 模块,其余两模块都比较简单。库中包含websocket封装部分,详细信息请点击跳转至 基于OKHttp的websocket封装使用 。
接入方式
1.导入hsjokhttp module。
- 注意module中gradle文件里,对okhttp等一系列第三方库的依赖不要丢。
implementation 'com.squareup.okhttp3:okhttp:4.2.2'
implementation "io.reactivex.rxjava2:rxjava:2.2.0"
implementation "io.reactivex.rxjava2:rxandroid:2.1.0"
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
其中依赖的版本号,可结合自己项目的实际情况更新。日志打印module可以去掉,或者自己调整。我在网络库中依赖它是因为这个logger支持长文本及格式化打印网络请求等信息,查看非常方便。
- 因为网络库中封装了CacheInterceptor,这个Interceptor里面有判断网络连接状态,所以需要在module中AndroidManifest.xml文件添加ACCESS_NETWORK_STATE权限。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hsj.okhttp" >
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
2.接入使用
- 在项目的app(主) module的gradle文件中依赖网络库及其他相关库。
implementation "io.reactivex.rxjava2:rxjava:2.2.0"
implementation "io.reactivex.rxjava2:rxandroid:2.1.0"
implementation 'com.squareup.okhttp3:okhttp:4.2.2'
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
implementation project(path: ':hsjokhttp')
implementation project(path: ':bean')
implementation project(path: ':hsjlogger')
- 新建OkHttpApi接口文件,定义各网络请求接口。
public interface OkHttpApi {
//get请求方式
@GET(NetConstants.URL_GET_TOKEN)
Observable<ResponseBody> getToken();
//获取短信验证码
@POST("code/sms")
@FormUrlEncoded
Observable<ResponseBody> getCodeSms(@FieldMap Map<String, String> bean);
//某维度下的标签
@POST("story/tag/dimension/notlogin")
Observable<ResponseBody> getTag(@Body RequestBody bean);
//上传头像图片
@POST("helper/upload/file/resource")
Observable<ResponseBody> uploadImgFile(@Body MultipartBody multipartBody);
}
- 新建BaseSubscribe文件,主要是基于网络库创建client,生成实例化网络请求的API。具体请看完整示例代码。
public class BaseSubscribe {
public static MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final String TOKEN = "";
private static final String USERID = "";
private static OkHttpApi okHttpApi;
public static OkHttpApi getOkHttpApi() {
if (okHttpApi==null) {
okHttpApi = newApi(NetConstants.BASE_URL, getHeaderParams(TOKEN, USERID), OkHttpApi.class);
}
return okHttpApi;
}
/**
* 关键方法,可以根据需求产出不同的api
* @param baseUrl
* @param params
* @param apiClass
* @param <T>
* @return
*/
public static <T>T newApi(String baseUrl, Map<String, String> params, Class<T> apiClass) {
NetBuilder builder = new NetBuilder()
.setConnectTimeout(HsjNetConstants.DEFAULT_CONNECT_TIMEOUT)
.setReadTimeout(HsjNetConstants.DEFAULT_READ_TIMEOUT)
.setWriteTimeout(HsjNetConstants.DEFAULT_WRITE_TIMEOUT)
.setRetryOnConnectionFailure(true);
//添加header
if (params != null && params.size()>0) {
HeaderInterceptor headerInterceptor = new HeaderInterceptor(params);
builder.addInterceptor(headerInterceptor);
}
//添加缓存
File cacheFile = new File(App.getAppContext().getExternalCacheDir(), HsjNetConstants.CACHE_NAME);
Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
builder.addCache(cache);
//添加缓存拦截器
CacheInterceptor cacheInterceptor = new CacheInterceptor(App.getAppContext());
builder.addInterceptor(cacheInterceptor);
// builder.addNetInterceptor(new NetInterceptor());
return builder.build(baseUrl).create(apiClass);
}
private static Map<String, String> getHeaderParams(String token, String userId) {
String timestamp, signature;
timestamp = String.valueOf(System.currentTimeMillis() / 1000);
Map<String, String> params = new HashMap<>();
if (!TextUtils.isEmpty(token)) {
params.put("token", token);
}
if (!TextUtils.isEmpty(userId) && !"null".equals