基线备份:thirdparty 变体完成 + Android 4.2 兼容改造前
包含内容: - thirdparty flavor 独立 applicationId + Intent 入口(ThirdPartyEntryActivity) - 58 后端接口适配(单 /api 路径、code 0/200、camelCase 字段、UNBOUND 轮询) - MAC 硬件锚定校验(防一凭证多设备共用) - EPG mac 覆盖 SDK init(sMacOverride)+ ChannelManger 初始化对齐 - 提示文案优化(设备未注册/权益未绑定)
This commit is contained in:
29
libdata/src/main/java/com/migu/libnetwork/AnHuiApi.java
Executable file
29
libdata/src/main/java/com/migu/libnetwork/AnHuiApi.java
Executable file
@@ -0,0 +1,29 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import io.reactivex.rxjava3.core.Observable;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.ResponseBody;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.Body;
|
||||
import retrofit2.http.POST;
|
||||
import retrofit2.http.Path;
|
||||
|
||||
/**
|
||||
* create by xujiangyun at 2024/1/19
|
||||
* 安徽api
|
||||
*/
|
||||
|
||||
public interface AnHuiApi {
|
||||
|
||||
//鉴权
|
||||
@POST("UserAndProdCheck")
|
||||
Call<ResponseBody> authOrize(@Body RequestBody body);
|
||||
|
||||
//足迹
|
||||
@POST("addBookmarks")
|
||||
Call<ResponseBody> historyReport(@Body RequestBody body);
|
||||
|
||||
//收藏
|
||||
@POST("addFavorites")
|
||||
Call<ResponseBody> collectReport(@Body RequestBody body);
|
||||
}
|
||||
136
libdata/src/main/java/com/migu/libnetwork/ApiService.java
Executable file
136
libdata/src/main/java/com/migu/libnetwork/ApiService.java
Executable file
@@ -0,0 +1,136 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import io.reactivex.rxjava3.core.Observable;
|
||||
import okhttp3.MultipartBody;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.ResponseBody;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.Response;
|
||||
import retrofit2.http.Body;
|
||||
import retrofit2.http.FieldMap;
|
||||
import retrofit2.http.FormUrlEncoded;
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Header;
|
||||
import retrofit2.http.Multipart;
|
||||
import retrofit2.http.POST;
|
||||
import retrofit2.http.Part;
|
||||
import retrofit2.http.PartMap;
|
||||
import retrofit2.http.Path;
|
||||
import retrofit2.http.Query;
|
||||
import retrofit2.http.QueryMap;
|
||||
import retrofit2.http.Streaming;
|
||||
import retrofit2.http.Url;
|
||||
|
||||
public interface ApiService {
|
||||
|
||||
@GET
|
||||
Observable<String> getPath(@Url String url);
|
||||
|
||||
// GET请求(无参) api = news
|
||||
@GET("{api}")
|
||||
Observable<String> getData(@Path("api") String api);
|
||||
|
||||
@GET
|
||||
Observable<String> getData(@Url String url,@Header("Cookie") String headers);
|
||||
|
||||
// GET请求(带参) api = news
|
||||
@GET("{api}")
|
||||
Observable<String> getData(@Path("api") String api, @QueryMap TreeMap<String, Object> map);
|
||||
|
||||
@GET
|
||||
Observable<String> getLoginData(@Url String url,@Header("tenant") String headers);
|
||||
@GET
|
||||
Observable<String> getIsLogin(@Url String url,@Header("tenant") String headers);
|
||||
@GET
|
||||
Observable<String> getPayResultCycle(@Url String url,@Header("Authorization") String headers,@Header("tenant") String tenant);
|
||||
|
||||
@GET
|
||||
Observable<String> getUserInfo(@Url String url,@Header("Authorization") String authorization,@Header("tenant") String tenant);
|
||||
|
||||
// POST请求(无参)
|
||||
@POST("{api}")
|
||||
Observable<String> postData(@Path(value = "api", encoded = true) String api);
|
||||
|
||||
|
||||
// POST请求,以RequestBody方式提交 api = news
|
||||
// RequestBody:
|
||||
// {
|
||||
// "albumID": 2,
|
||||
// "sectionID": 16
|
||||
// }
|
||||
@POST("{api}")
|
||||
Observable<String> postData(@Path(value = "api", encoded = true) String api, @Body RequestBody requestBody);
|
||||
|
||||
@POST
|
||||
Observable<String> postDataPath(@Url String url, @Body RequestBody requestBody);
|
||||
|
||||
@POST
|
||||
Observable<String> postDataPathHeader(@Url String url, @Body RequestBody requestBody,@Header("Authorization") String authorization);
|
||||
|
||||
@POST
|
||||
Observable<String> postDataPathSignHeader(@Url String url, @Body RequestBody requestBody, @Header("sign") String sign);
|
||||
|
||||
@POST
|
||||
Observable<String> postDataOrderList(@Url String url, @Header("Authorization") String authorization,@Header("tenant") String tenant);
|
||||
@POST
|
||||
Observable<String> postDataActivate(@Url String url,@Header("tenant") String tenant,@Body RequestBody requestBody);
|
||||
@POST
|
||||
Observable<String> postDataQueryVipInfo(@Url String url,@Header("tenant") String tenant);
|
||||
|
||||
@POST()
|
||||
Observable<String> postDataShanxi(@Url String url,
|
||||
@Header("timestamp") long timestamp,
|
||||
@Header("vsopPartnerId") String vsopPartnerId,
|
||||
@Header("vsopToken") String vsopToken,
|
||||
@Body RequestBody requestBody);
|
||||
|
||||
@POST("{api}")
|
||||
Observable<String> postDataWithHeaderToken(@Path(value = "api", encoded = true) String api, @Header("Authorization") String authorization, @Body RequestBody requestBody);
|
||||
|
||||
@POST("{api}")
|
||||
Observable<String> postDataWithHeaderMore(@Path(value = "api", encoded = true) String api,
|
||||
@Header("Authorization") String userToken,
|
||||
@Header("X_CSRFToken") String csrfToken,
|
||||
@Header("Cookie") String cookie,
|
||||
@Header("Content-Type") String contentType,
|
||||
@Header("Content-length") String contentLength,
|
||||
@Body RequestBody requestBody);
|
||||
|
||||
@POST()
|
||||
Observable<String> postCloudLogin(@Url String url,
|
||||
@Header("tenant") String tenant,
|
||||
@Header("encryptData") String signature,
|
||||
@Body RequestBody requestBody);
|
||||
|
||||
|
||||
// Post请求,以表单方式提交
|
||||
@FormUrlEncoded
|
||||
@POST("{api}")
|
||||
Observable<ResponseBody> postData(@Path("api") String api, @FieldMap Map<String, String> maps);
|
||||
|
||||
|
||||
// Post请求(带数组)
|
||||
@FormUrlEncoded
|
||||
@POST("{api}")
|
||||
Observable<ResponseBody> postData(@Path("api") String api, @FieldMap Map<String, String> maps, @Query("meta[]") String... linked);
|
||||
|
||||
// 上传单个文件
|
||||
@Multipart
|
||||
@POST("{api}/")
|
||||
Observable<String> upload(@Path("api") String api, @PartMap Map<String, RequestBody> maps, @Part MultipartBody.Part file);
|
||||
|
||||
// 上传多个文件
|
||||
@Multipart
|
||||
@POST("{api}/")
|
||||
Observable<String> uploadMultipart(@Path("api") String api, @PartMap Map<String, RequestBody> maps, @Part List<MultipartBody.Part> params);
|
||||
|
||||
//下载文件
|
||||
@Streaming //大文件时要加不然会OOM
|
||||
@GET
|
||||
Observable<ResponseBody> downloadFile(@Url String fileUrl);
|
||||
}
|
||||
40
libdata/src/main/java/com/migu/libnetwork/GuangDongApi.java
Executable file
40
libdata/src/main/java/com/migu/libnetwork/GuangDongApi.java
Executable file
@@ -0,0 +1,40 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.ResponseBody;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.Body;
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Header;
|
||||
import retrofit2.http.POST;
|
||||
import retrofit2.http.Query;
|
||||
import retrofit2.http.Url;
|
||||
|
||||
|
||||
public interface GuangDongApi {
|
||||
@POST("/EPG/interEpg/user/default/authorize")
|
||||
Call<ResponseBody> authOrizeplay(@Header("Authorization") String token, @Body RequestBody body);
|
||||
|
||||
@POST("/EPG/interEpg/channellist/batch")
|
||||
Call<ResponseBody> authOrizeLive(@Header("Authorization") String token, @Body RequestBody body);
|
||||
|
||||
@POST("auth?appId=35329553&appKey=5swxou31")
|
||||
Call<ResponseBody> authOrize(@Header("sign") String header, @Body RequestBody body);
|
||||
|
||||
@POST("order?appId=35329553&appKey=5swxou31")
|
||||
Call<ResponseBody> order(@Header("sign") String header, @Body RequestBody body);
|
||||
|
||||
@GET // 广东iptv中兴平台获取播放地址
|
||||
Call<ResponseBody> authOrizeplay(@Url String url);
|
||||
|
||||
@GET("/iptvepg/function/MediaService/get_playurl.jsp")
|
||||
Call<ResponseBody> authOrizeplayIptv(
|
||||
@Query("jsessionid") String jsessionid,
|
||||
@Query("ContentID") int contentId,
|
||||
@Query("ContentType") String contentType,
|
||||
@Query("UserToken") String userToken,
|
||||
@Query("ProtocolType") int protocolType,
|
||||
@Query("Type") String type
|
||||
);
|
||||
|
||||
}
|
||||
14
libdata/src/main/java/com/migu/libnetwork/HaiNanApi.java
Executable file
14
libdata/src/main/java/com/migu/libnetwork/HaiNanApi.java
Executable file
@@ -0,0 +1,14 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.ResponseBody;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.Body;
|
||||
import retrofit2.http.Header;
|
||||
import retrofit2.http.POST;
|
||||
|
||||
|
||||
public interface HaiNanApi {
|
||||
@POST("/EPG/interEpg/user/default/authorize")
|
||||
Call<ResponseBody> authorizePlay(@Header("Authorization") String token, @Body RequestBody body);
|
||||
}
|
||||
18
libdata/src/main/java/com/migu/libnetwork/HeNanApi.java
Executable file
18
libdata/src/main/java/com/migu/libnetwork/HeNanApi.java
Executable file
@@ -0,0 +1,18 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.ResponseBody;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.Body;
|
||||
import retrofit2.http.POST;
|
||||
|
||||
|
||||
public interface HeNanApi {
|
||||
|
||||
/**
|
||||
* 上报用户信息接口
|
||||
* */
|
||||
@POST("activeUser/reportUser.do")
|
||||
Call<ResponseBody> reportUser(@Body RequestBody body);
|
||||
|
||||
}
|
||||
20
libdata/src/main/java/com/migu/libnetwork/HeiLongJiangApi.java
Executable file
20
libdata/src/main/java/com/migu/libnetwork/HeiLongJiangApi.java
Executable file
@@ -0,0 +1,20 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import com.migu.bean.AuthorizeNewBean;
|
||||
|
||||
import io.reactivex.rxjava3.core.Observable;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.ResponseBody;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.Body;
|
||||
import retrofit2.http.Header;
|
||||
import retrofit2.http.POST;
|
||||
|
||||
|
||||
public interface HeiLongJiangApi {
|
||||
/**
|
||||
* 黑龙江点播获取播放地址 【华为接口】
|
||||
* **/
|
||||
@POST("/EPG/interEpg/user/default/authorize")
|
||||
Call<ResponseBody> authorizePlay(@Header("Authorization") String token, @Body RequestBody body);
|
||||
}
|
||||
14
libdata/src/main/java/com/migu/libnetwork/HttpRequestCallback.java
Executable file
14
libdata/src/main/java/com/migu/libnetwork/HttpRequestCallback.java
Executable file
@@ -0,0 +1,14 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
/**
|
||||
* content: 请求接口回调
|
||||
*/
|
||||
public interface HttpRequestCallback {
|
||||
|
||||
void onRequestNetFail(int type);
|
||||
|
||||
void onRequestSuccess(String result, int type);
|
||||
|
||||
void onRequestFail(String value, String failCode, int type);
|
||||
|
||||
}
|
||||
20
libdata/src/main/java/com/migu/libnetwork/HttpRequestConstants.java
Executable file
20
libdata/src/main/java/com/migu/libnetwork/HttpRequestConstants.java
Executable file
@@ -0,0 +1,20 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import com.pukka.libcore.base.BaseUrl;
|
||||
|
||||
/**
|
||||
* content: 网络请求的常量类
|
||||
*/
|
||||
public class HttpRequestConstants {
|
||||
|
||||
// public static String BASE_URL = "http://36.155.98.104:11283/";
|
||||
public static String BASE_URL = BaseUrl.getSingleton().getBaseHttpUrl();
|
||||
public static final String SECRET = " ";
|
||||
public static final String APP_KEY = " ";
|
||||
|
||||
public static final String SIGN_METHOD_MD5 = "MD5";
|
||||
public static final String SIGN_METHOD_HMAC = "HMAC";
|
||||
public static final String CHARSET_UTF8 = "UTF-8";
|
||||
|
||||
public static final String TAG = "RequestError";
|
||||
}
|
||||
22
libdata/src/main/java/com/migu/libnetwork/HttpRequestFileCallback.java
Executable file
22
libdata/src/main/java/com/migu/libnetwork/HttpRequestFileCallback.java
Executable file
@@ -0,0 +1,22 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* content: 请求接口回调
|
||||
*/
|
||||
public interface HttpRequestFileCallback {
|
||||
|
||||
void onRequestNetFail(int type);
|
||||
|
||||
void onProgress(int progress);
|
||||
|
||||
void onComplete(File file);
|
||||
|
||||
void onStart();
|
||||
|
||||
void downFail();
|
||||
|
||||
void onRequestFail(String value, String failCode, int type);
|
||||
|
||||
}
|
||||
26
libdata/src/main/java/com/migu/libnetwork/HttpRequestInterceptor.java
Executable file
26
libdata/src/main/java/com/migu/libnetwork/HttpRequestInterceptor.java
Executable file
@@ -0,0 +1,26 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
/**
|
||||
* content: 拦截每次发出的请求并打印出来
|
||||
*/
|
||||
public class HttpRequestInterceptor implements Interceptor {
|
||||
private static final String SPU = "HttpRequestInterceptor";
|
||||
|
||||
@Override
|
||||
public Response intercept(Chain chain) throws IOException {
|
||||
Request request = chain.request();
|
||||
Response response;
|
||||
long startTime = System.currentTimeMillis();
|
||||
response = chain.proceed(chain.request());
|
||||
okhttp3.MediaType mediaType = response.body().contentType();
|
||||
String content = response.body().string();
|
||||
NetUtil.printHttpLog(true, startTime, request, content);
|
||||
return response.newBuilder().body(okhttp3.ResponseBody.create(mediaType, content)).build();
|
||||
}
|
||||
}
|
||||
69
libdata/src/main/java/com/migu/libnetwork/HttpRetrofit.java
Executable file
69
libdata/src/main/java/com/migu/libnetwork/HttpRetrofit.java
Executable file
@@ -0,0 +1,69 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import retrofit2.Converter;
|
||||
|
||||
/**
|
||||
* content: 用于获取Retrofit的ApiService的类
|
||||
*/
|
||||
public class HttpRetrofit {
|
||||
|
||||
// 设置数据读取超时时间
|
||||
public HttpRetrofit setTimeOutTime(long timeout) {
|
||||
OkHttpClientUtil.getOkHttpUtil().setTimeOutTime(timeout);
|
||||
return this;
|
||||
}
|
||||
|
||||
// 设置网络连接超时时间
|
||||
public HttpRetrofit setConnectTime(long timeout) {
|
||||
OkHttpClientUtil.getOkHttpUtil().setConnectTime(timeout);
|
||||
return this;
|
||||
}
|
||||
|
||||
// 设置写入服务器的超时时间
|
||||
public HttpRetrofit setWriteTime(long timeout) {
|
||||
OkHttpClientUtil.getOkHttpUtil().setWriteTime(timeout);
|
||||
return this;
|
||||
}
|
||||
|
||||
// 设置拦截器
|
||||
public HttpRetrofit setIntercept(boolean isIntercept) {
|
||||
OkHttpClientUtil.getOkHttpUtil().setIntercept(isIntercept);
|
||||
return this;
|
||||
}
|
||||
|
||||
// 设置BaseUrl
|
||||
public HttpRetrofit setBaseUrl(String baseUrl) {
|
||||
RetrofitClientUtil.getRetrofitUtil().setBaseUrl(baseUrl);
|
||||
return this;
|
||||
}
|
||||
|
||||
// 设置数据解析
|
||||
public HttpRetrofit addConverterFactory(Converter.Factory factory) {
|
||||
RetrofitClientUtil.getRetrofitUtil().addConverterFactory(factory);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成请求接口的实例
|
||||
* @return ApiService
|
||||
*/
|
||||
public ApiService getApiManager(){
|
||||
return RetrofitClientUtil.getRetrofitUtil().setOkHttpClient(OkHttpClientUtil.getOkHttpUtil().build()).build().create(ApiService.class);
|
||||
}
|
||||
|
||||
// public ApiService getV2ApiManager(){
|
||||
// return RetrofitClientUtil.getRetrofitUtil().setOkHttpClient(OkHttpClientUtil.getOkHttpUtil().build()).noBaseurlBuild().create(ApiService.class);
|
||||
// }
|
||||
|
||||
// public ApiService getV2HttpsApiManager(){
|
||||
// return RetrofitClientUtil.getRetrofitUtil().setOkHttpClient(OkHttpSsl.getUnsafeOkHttpClient()).noBaseurlBuild().create(ApiService.class);
|
||||
// }
|
||||
|
||||
public ApiService getHttpsApiManager(){
|
||||
return RetrofitClientUtil.getRetrofitUtil().setOkHttpClient(OkHttpSsl.getUnsafeOkHttpClient()).build().create(ApiService.class);
|
||||
}
|
||||
|
||||
public ApiService getFileApiManager(){
|
||||
return RetrofitClientUtil.getRetrofitUtil().setOkHttpClient(OkHttpClientUtil.getOkHttpUtil().fileBuild()).build().create(ApiService.class);
|
||||
}
|
||||
}
|
||||
341
libdata/src/main/java/com/migu/libnetwork/HttpRetrofitRequest.java
Executable file
341
libdata/src/main/java/com/migu/libnetwork/HttpRetrofitRequest.java
Executable file
@@ -0,0 +1,341 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
|
||||
import io.reactivex.rxjava3.core.Observable;
|
||||
import io.reactivex.rxjava3.disposables.Disposable;
|
||||
import io.reactivex.rxjava3.schedulers.Schedulers;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.MultipartBody;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.ResponseBody;
|
||||
|
||||
/**
|
||||
* content:用于发起网络请求的中间工具类
|
||||
*/
|
||||
public class HttpRetrofitRequest extends HttpRetrofit implements IHttpRequest {
|
||||
private ApiService jcApiService;
|
||||
private ApiService apiService;
|
||||
//private ApiService v2ApiService;
|
||||
private ApiService fileApiService;
|
||||
// 是否添加通用参数
|
||||
private boolean mIsAddCommonParams;
|
||||
|
||||
private volatile static HttpRetrofitRequest INSTANCES;
|
||||
|
||||
public static HttpRetrofitRequest getInstances() {
|
||||
if (INSTANCES == null) {
|
||||
synchronized (HttpRetrofitRequest.class) {
|
||||
if (INSTANCES == null) {
|
||||
INSTANCES = new HttpRetrofitRequest();
|
||||
}
|
||||
}
|
||||
}
|
||||
return INSTANCES;
|
||||
}
|
||||
|
||||
private HttpRetrofitRequest() {
|
||||
apiService = getApiManager();
|
||||
//v2ApiService = getV2ApiManager();
|
||||
fileApiService = getFileApiManager();
|
||||
jcApiService = getHttpsApiManager();
|
||||
}
|
||||
|
||||
public void setHttpBaseUrl(String url) {
|
||||
RetrofitClientUtil.getRetrofitUtil().setBaseUrl(url);
|
||||
if (url.contains("https")) {
|
||||
apiService = getHttpsApiManager();
|
||||
//v2ApiService = getV2HttpsApiManager();
|
||||
} else {
|
||||
apiService = getApiManager();
|
||||
//v2ApiService = getV2ApiManager();
|
||||
}
|
||||
fileApiService = getFileApiManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置通用参数
|
||||
*/
|
||||
public void isAddCommonParams(boolean isAddCommonParams) {
|
||||
this.mIsAddCommonParams = isAddCommonParams;
|
||||
}
|
||||
|
||||
// Get请求(使用Path形式)
|
||||
@Override
|
||||
public void mHttpGetPath(String url, int type, HttpRequestCallback callBack) {
|
||||
if (url.startsWith("https")){
|
||||
ApiService service = getHttpsApiManager();
|
||||
Observable<String> observable = service.getPath(url);
|
||||
observable.retryWhen(new RetryFunction(url)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}else {
|
||||
Observable<String> observable = apiService.getPath(url);
|
||||
observable.retryWhen(new RetryFunction(url)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// GET请求(无参)
|
||||
@Override
|
||||
public void mHttpGet(String api, int type, HttpRequestCallback callBack) {
|
||||
Observable<String> observable = apiService.getData(api);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}
|
||||
|
||||
// GET请求(带headers)
|
||||
@Override
|
||||
public void mHttpGet(String api, String headers, HttpRequestCallback callBack) {
|
||||
Observable<String> observable = apiService.getData(api,headers);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(0, callBack));
|
||||
}
|
||||
|
||||
// GET请求(带headers)
|
||||
@Override
|
||||
public void mHttpGetLogin(String api, String headers, HttpRequestCallback callBack) {
|
||||
ApiService LoginService = getHttpsApiManager();
|
||||
Observable<String> observable = LoginService.getLoginData(api,headers);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(0, callBack));
|
||||
}
|
||||
@Override
|
||||
public void mHttpIsLogin(String api, String headers, HttpRequestCallback callBack) {
|
||||
ApiService LoginService = getHttpsApiManager();
|
||||
Observable<String> observable = LoginService.getIsLogin(api,headers);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(0, callBack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mHttpGetPayResultCycle(String api, String headers,String tenant, HttpRequestCallback mCallBack) {
|
||||
Observable<String> observable = jcApiService.getPayResultCycle(api,headers,tenant);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(0, mCallBack));
|
||||
}
|
||||
|
||||
|
||||
// GET请求(带headers)
|
||||
@Override
|
||||
public void mHttpGetUserInfo(String api, String token,String headers, HttpRequestCallback callBack) {
|
||||
ApiService LoginService = getHttpsApiManager();
|
||||
Observable<String> observable = LoginService.getUserInfo(api,token,headers);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(0, callBack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mHttpDownFile(String url, int type, HttpRequestFileCallback mCallBack) {
|
||||
Observable<ResponseBody> observable = fileApiService.downloadFile(url);
|
||||
observable.retryWhen(new RetryFunction(url)).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new RxJavaFileObserver(type, mCallBack));
|
||||
}
|
||||
|
||||
// Get请求(带参)
|
||||
@Override
|
||||
public void mHttpGet(String api, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
if (mIsAddCommonParams) {
|
||||
HttpTool.getTreeCrc(map);
|
||||
}
|
||||
Observable<String> observable = apiService.getData(api, map);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}
|
||||
|
||||
// Post请求(无参)
|
||||
@Override
|
||||
public void mHttpPost(String api, int type, HttpRequestCallback callBack) {
|
||||
Observable<String> observable = apiService.postData(api);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}
|
||||
|
||||
// Post请求(带参)
|
||||
// 以RequestBody方式提交
|
||||
@Override
|
||||
public void mHttpPost(String api, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
if (mIsAddCommonParams) {
|
||||
HttpTool.getTreeCrc(map);
|
||||
}
|
||||
Gson gson = new Gson();
|
||||
String param = gson.toJson(map);
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param);
|
||||
Observable<String> observable = apiService.postData(api, requestBody);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}
|
||||
|
||||
// Post请求(带参)
|
||||
// 以RequestBody方式提交(超时不需要重试)
|
||||
@Override
|
||||
public void mHttpPostNoRetry(String api, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
if (mIsAddCommonParams) {
|
||||
HttpTool.getTreeCrc(map);
|
||||
}
|
||||
Gson gson = new Gson();
|
||||
String param = gson.toJson(map);
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param);
|
||||
Observable<String> observable = apiService.postData(api, requestBody);
|
||||
observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}
|
||||
// POST请求(带全地址,带headers)
|
||||
@Override
|
||||
public void mHttpPostShanxi(String url,String postParam,long timestamp,String vsopPartnerId,String vsopToken, HttpRequestCallback callBack) {
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postParam);
|
||||
Observable<String> observable = apiService.postDataShanxi(url,timestamp,vsopPartnerId,vsopToken,requestBody);
|
||||
observable.retryWhen(new RetryFunction(url)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(0, callBack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mHttpPostPath(String url, TreeMap map, int type, HttpRequestCallback mCallBack) {
|
||||
if (mIsAddCommonParams) {
|
||||
HttpTool.getTreeCrc(map);
|
||||
}
|
||||
Gson gson = new Gson();
|
||||
String param = gson.toJson(map);
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param);
|
||||
Observable<String> observable = apiService.postDataPath(url, requestBody);
|
||||
observable.retryWhen(new RetryFunction(url)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, mCallBack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mHttpPostPathHeader(String url, String content, String header, int type, HttpRequestCallback mCallBack) {
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), content);
|
||||
Observable<String> observable = apiService.postDataPathHeader(url, requestBody, header);
|
||||
observable.retryWhen(new RetryFunction(url)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, mCallBack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mHttpPostPathSignHeader(String url, String content, String sign, int type, HttpRequestCallback mCallBack) {
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), content);
|
||||
Observable<String> observable = apiService.postDataPathSignHeader(url, requestBody, sign);
|
||||
observable.retryWhen(new RetryFunction(url)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, mCallBack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mHttpPostOrderList(String api, String token, String tenant, HttpRequestCallback callBack) {
|
||||
Observable<String> observable = jcApiService.postDataOrderList(api,token,tenant);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(0, callBack));
|
||||
}
|
||||
@Override
|
||||
public void mHttpPostActivate(String api, String content,String tenant, HttpRequestCallback callBack) {
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), content);
|
||||
Observable<String> observable = jcApiService.postDataActivate(api,tenant,requestBody);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(0, callBack));
|
||||
}
|
||||
@Override
|
||||
public void mHttpPostQueryVipInfo(String api, String tenant, HttpRequestCallback callBack) {
|
||||
//RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), content);
|
||||
Observable<String> observable = jcApiService.postDataQueryVipInfo(api,tenant);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(0, callBack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mHttpPost(String api, String postParam, int type, HttpRequestCallback callBack) {
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postParam);
|
||||
Observable<String> observable = apiService.postData(api, requestBody);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mHttpPostWithHeaderToken(String api, String param, int type, String token, HttpRequestCallback callBack) {
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param);
|
||||
Observable<String> observable = apiService.postDataWithHeaderToken(api, token, requestBody);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mHttpPostWithHeaderMore(String api, String postParam, int type, String userToken, String csrfToken, String sessionId, HttpRequestCallback callBack) {
|
||||
String contentType = "application/json; charset=utf-8";
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse(contentType), postParam);
|
||||
String cookie = "JSESSIONID=" + sessionId;
|
||||
byte[] jsonData = postParam.getBytes();
|
||||
String contentLength = String.valueOf(jsonData.length);
|
||||
Observable<String> observable = apiService.postDataWithHeaderMore(api, userToken, csrfToken, cookie, contentType, contentLength, requestBody);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mHttpPostCloudLogin(String api, TreeMap map, String tenant, String signature, HttpRequestCallback callBack) {
|
||||
Gson gson = new Gson();
|
||||
String postParam = gson.toJson(map);
|
||||
String contentType = "application/json; charset=utf-8";
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse(contentType), postParam);
|
||||
Observable<String> observable = jcApiService.postCloudLogin(api, tenant, signature,requestBody);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(1, callBack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mV2HttpPost(String api, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
// if (mIsAddCommonParams) {
|
||||
// HttpTool.getTreeCrc(map);
|
||||
// }
|
||||
// Gson gson = new Gson();
|
||||
// String param = gson.toJson(map);
|
||||
// RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param);
|
||||
// Observable<String> observable = v2ApiService.postData(api, requestBody);
|
||||
// observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Disposable mHttpPostDisposable(String api, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
if (mIsAddCommonParams) {
|
||||
HttpTool.getTreeCrc(map);
|
||||
}
|
||||
Gson gson = new Gson();
|
||||
String param = gson.toJson(map);
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param);
|
||||
Observable<String> observable = apiService.postData(api, requestBody);
|
||||
RxJavaObserver rxJavaObserver = new RxJavaObserver(type, callBack);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(rxJavaObserver);
|
||||
return rxJavaObserver.getDisposable();
|
||||
}
|
||||
|
||||
// Post请求(包含数组)
|
||||
@Override
|
||||
public void mHttpPost(String api, TreeMap map, String[] data, int type, HttpRequestCallback callBack) {
|
||||
if (mIsAddCommonParams) {
|
||||
HttpTool.getTreeCrc(map);
|
||||
}
|
||||
Observable<String> observable = apiService.postData(api, map, data);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}
|
||||
|
||||
// 单文件上传
|
||||
@Override
|
||||
public void mHttpFile(String api, File file, String fileKey, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
// 生成单个文件
|
||||
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
|
||||
MultipartBody.Part body = MultipartBody.Part.createFormData(fileKey, file.getName(), requestFile);
|
||||
|
||||
if (mIsAddCommonParams) {
|
||||
HttpTool.getTreeCrc(map);
|
||||
}
|
||||
Map<String, RequestBody> mapValue = new HashMap<>();
|
||||
for (Object key : map.keySet()) {
|
||||
mapValue.put(key.toString(), HttpTool.convertToRequestBody(map.get(key).toString()));
|
||||
}
|
||||
Observable<String> observable = apiService.upload(api, mapValue, body);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}
|
||||
|
||||
// 多文件上传
|
||||
@Override
|
||||
public void mHttpMultiFile(String api, List<File> list, List<String> listFileName, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
//生成多个文件并添加到集合中
|
||||
List<MultipartBody.Part> params = new ArrayList<>();
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), list.get(i));
|
||||
MultipartBody.Part body = MultipartBody.Part.createFormData(listFileName.get(i), list.get(i).getName(), requestFile);
|
||||
params.add(body);
|
||||
}
|
||||
if (mIsAddCommonParams) {
|
||||
HttpTool.getTreeCrc(map);
|
||||
}
|
||||
Map<String, RequestBody> mapValue = new HashMap<>();
|
||||
for (Object key : map.keySet()) {
|
||||
mapValue.put(key.toString(), HttpTool.convertToRequestBody(Objects.requireNonNull(map.get(key)).toString()));
|
||||
}
|
||||
// 发送异步请求
|
||||
Observable<String> observable = apiService.uploadMultipart(api, mapValue, params);
|
||||
observable.retryWhen(new RetryFunction(api)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxJavaObserver(type, callBack));
|
||||
}
|
||||
}
|
||||
196
libdata/src/main/java/com/migu/libnetwork/HttpTool.java
Executable file
196
libdata/src/main/java/com/migu/libnetwork/HttpTool.java
Executable file
@@ -0,0 +1,196 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.NetworkInfo;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.pukka.libcore.utils.ContextUtils;
|
||||
import com.pukka.libcore.utils.DateUtils;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.RequestBody;
|
||||
|
||||
/**
|
||||
* 工具类 (添加通用参数、加密等等)
|
||||
*/
|
||||
public class HttpTool {
|
||||
|
||||
public static RequestBody convertToRequestBody(String param) {
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), param);
|
||||
return requestBody;
|
||||
}
|
||||
|
||||
public static String signTopRequest(Map<String, Object> params, String secret, String signMethod) throws IOException {
|
||||
// 第一步:检查参数是否已经排序
|
||||
String[] keys = params.keySet().toArray(new String[0]);
|
||||
Arrays.sort(keys);
|
||||
|
||||
// 第二步:把所有参数名和参数值串在一起
|
||||
StringBuilder query = new StringBuilder();
|
||||
for (String key : keys) {
|
||||
Object value = params.get(key);
|
||||
if (value instanceof String) {
|
||||
if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty((String) value)) {
|
||||
query.append(key).append(value);
|
||||
}
|
||||
} else if (value instanceof File) {
|
||||
String strVal = getFileContent((File) value);
|
||||
query.append(key).append(strVal);
|
||||
params.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
// 第三步:使用MD5/HMAC加密
|
||||
byte[] bytes;
|
||||
if (HttpRequestConstants.SIGN_METHOD_HMAC.equals(signMethod)) {
|
||||
bytes = encryptHMAC(query.toString(), secret);
|
||||
} else {
|
||||
bytes = encryptMD5(query.toString() + secret);
|
||||
}
|
||||
|
||||
// 第四步:把二进制转化为大写的十六进制
|
||||
return byte2hex(bytes);
|
||||
}
|
||||
|
||||
public static byte[] encryptHMAC(String data, String secret) throws IOException {
|
||||
byte[] bytes = null;
|
||||
try {
|
||||
SecretKey secretKey = new SecretKeySpec(secret.getBytes(HttpRequestConstants.CHARSET_UTF8), "HmacMD5");
|
||||
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
|
||||
mac.init(secretKey);
|
||||
bytes = mac.doFinal(data.getBytes(HttpRequestConstants.CHARSET_UTF8));
|
||||
} catch (GeneralSecurityException gse) {
|
||||
throw new IOException(gse.toString());
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public static byte[] encryptMD5(String data) throws IOException {
|
||||
byte[] md5Byte = null;
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("MD5"); // 创建一个md5算法对象
|
||||
byte[] messageByte = data.getBytes("UTF-8");
|
||||
md5Byte = md.digest(messageByte); // 获得MD5字节数组,16*8=128位
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return md5Byte;
|
||||
}
|
||||
|
||||
public static String byte2hex(byte[] bytes) {
|
||||
StringBuilder sign = new StringBuilder();
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
String hex = Integer.toHexString(bytes[i] & 0xFF);
|
||||
if (hex.length() == 1) {
|
||||
sign.append("0");
|
||||
}
|
||||
sign.append(hex.toLowerCase());
|
||||
}
|
||||
return sign.toString();
|
||||
}
|
||||
|
||||
public static TreeMap getTreeCrc(TreeMap maps) {
|
||||
try {
|
||||
maps.put("app_key", HttpRequestConstants.APP_KEY);
|
||||
maps.put("sign_method", "md5");
|
||||
maps.put("format", "json");
|
||||
maps.put("timestamp", DateUtils.getStringNowDateInShanghai());
|
||||
maps.put("sign", signTopRequest(maps, HttpRequestConstants.SECRET, HttpRequestConstants.SIGN_METHOD_MD5));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return maps;
|
||||
}
|
||||
|
||||
// 检测是否有网络
|
||||
@SuppressLint("MissingPermission")
|
||||
public static boolean hasNetwork() {
|
||||
// 得到连接管理器对象
|
||||
if(null == ContextUtils.getContext()){
|
||||
return false;
|
||||
}
|
||||
ConnectivityManager connectivityManager = (ConnectivityManager) ContextUtils.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
|
||||
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
|
||||
if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
|
||||
return true;
|
||||
} else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
|
||||
return true;
|
||||
} else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_ETHERNET)) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// 将文件进行SHA1加密
|
||||
public static String getFileContent(File file) {
|
||||
try {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-1");
|
||||
FileInputStream fin = new FileInputStream(file);
|
||||
int len = -1;
|
||||
byte[] buffer = new byte[1024];//设置输入流的缓存大小 字节
|
||||
//将整个文件全部读入到加密器中
|
||||
while ((len = fin.read(buffer)) != -1) {
|
||||
digest.update(buffer, 0, len);
|
||||
}
|
||||
//对读入的数据进行加密
|
||||
byte[] bytes = digest.digest();
|
||||
for (byte b : bytes) {
|
||||
// 数byte 类型转换为无符号的整数
|
||||
int n = b & 0XFF;
|
||||
// 将整数转换为16进制
|
||||
String s = Integer.toHexString(n);
|
||||
// 如果16进制字符串是一位,那么前面补0
|
||||
if (s.length() == 1) {
|
||||
sb.append("0" + s);
|
||||
} else {
|
||||
sb.append(s);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 2 * 判断字符串是否可以转化为json对象
|
||||
* 3 * @param content
|
||||
* 4 * @return
|
||||
* 5
|
||||
*/
|
||||
public static boolean isJsonObject(String content) {
|
||||
if (content == null || TextUtils.isEmpty(content)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
JSONObject jsonObject = new JSONObject(content);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
405
libdata/src/main/java/com/migu/libnetwork/HttpUtils.java
Executable file
405
libdata/src/main/java/com/migu/libnetwork/HttpUtils.java
Executable file
@@ -0,0 +1,405 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import com.pukka.libcore.base.BaseUrl;
|
||||
import com.pukka.libcore.utils.LogUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import io.reactivex.rxjava3.disposables.Disposable;
|
||||
import okhttp3.Callback;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
|
||||
/**
|
||||
* 用于发起网络请求的基础工具类
|
||||
*/
|
||||
public class HttpUtils {
|
||||
|
||||
private static IHttpRequest mHttpRequest;
|
||||
|
||||
/**
|
||||
* 生成唯一实例
|
||||
*/
|
||||
private static volatile HttpUtils mInstance;
|
||||
|
||||
public static HttpUtils getInstance() {
|
||||
if (mInstance == null) {
|
||||
synchronized (HttpUtils.class) {
|
||||
if (mInstance == null) {
|
||||
mInstance = new HttpUtils();
|
||||
}
|
||||
}
|
||||
}
|
||||
return mInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化决定使用哪一套网络请求框架
|
||||
*
|
||||
* @param httpRequest 默认为OkHttp + retrofit + rxJava
|
||||
*/
|
||||
public static void setInitHttpRequest(IHttpRequest httpRequest) {
|
||||
mHttpRequest = httpRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更换使用的框架
|
||||
*
|
||||
* @param httpRequest 重新设置的网络框架
|
||||
* @return
|
||||
*/
|
||||
public HttpUtils httpRequest(IHttpRequest httpRequest) {
|
||||
mHttpRequest = httpRequest;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get请求(使用Path形式)
|
||||
*
|
||||
* @param url 请求的url地址,不使用baseUrl
|
||||
* @param type 请求的标识
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executePathGet(String url, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpGetPath(url, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GET请求(无参)
|
||||
*
|
||||
* @param api 请求的api
|
||||
* @param type 请求的标识
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executeGet(String api, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpGet(api, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GET请求(带headers)
|
||||
*
|
||||
* @param url 请求的api
|
||||
* @param cookie headers
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executeGet(String url, String cookie, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpGet(url, cookie, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GET请求(带headers)
|
||||
*
|
||||
* @param url 请求的api
|
||||
* @param cookie headers
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void mHttpGetLogin(String url, String cookie, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpGetLogin(url, cookie, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
public void mHttpIsLogin(String url, String cookie, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpIsLogin(url, cookie, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
public void mHttpGetPayResultCycle(String url, String header, String tenant, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpGetPayResultCycle(url, header, tenant, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
public void mHttpPostOrderList(String api, String token, String tenant, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPostOrderList(api, token, tenant, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
public void mHttpPostActivate(String api, String postParam, String tenant, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPostActivate(api, postParam, tenant, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
public void mHttpPostQueryVipInfo(String api, String tenant, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPostQueryVipInfo(api, tenant, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* GET请求(带headers)
|
||||
*
|
||||
* @param url 请求的api
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void mHttpGetUserInfo(String url, String token, String header, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpGetUserInfo(url, token, header, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get请求(带参)
|
||||
*
|
||||
* @param api 请求的api
|
||||
* @param map 请求的参数
|
||||
* @param type 请求的标识
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executeGet(String api, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpGet(api, map, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Post请求(无参)
|
||||
*
|
||||
* @param api 请求的api
|
||||
* @param type 请求的标识
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executePost(String api, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPost(api, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Post请求(带参)
|
||||
* 以RequestBody方式提交
|
||||
*
|
||||
* @param api 请求的api
|
||||
* @param map 请求的参数
|
||||
* @param type 请求的标识
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executePost(String api, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPost(api, map, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Post请求(带参)
|
||||
* 以RequestBody方式提交(超时不需要重试)
|
||||
*
|
||||
* @param api 请求的api
|
||||
* @param map 请求的参数
|
||||
* @param type 请求的标识
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executePostNoRetry(String api, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPostNoRetry(api, map, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
public void executePostPath(String url, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPostPath(url, map, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
public void executePostPathHeader(String url, String content, String header, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPostPathHeader(url, content, header, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
public void executePostPathSignHeader(String url, String content, String sign, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPostPathSignHeader(url, content, sign, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Post请求(带参)
|
||||
* 以RequestBody方式提交
|
||||
*
|
||||
* @param api 请求的api
|
||||
* @param postParam 请求的参数
|
||||
* @param type 请求的标识
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executePost(String api, String postParam, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPost(api, postParam, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
public void executePostCloudLogin(String api, TreeMap map, String tenant, String signature, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPostCloudLogin(api, map, tenant, signature, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Post请求(带参带header)
|
||||
* 以RequestBody方式提交
|
||||
*
|
||||
* @param api 请求的api
|
||||
* @param postParam 请求的参数
|
||||
* @param type 请求的标识
|
||||
* @param token token
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executePostWithHeaderToken(String api, String postParam, int type, String token, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPostWithHeaderToken(api, postParam, type, token, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Post请求(带参带header)
|
||||
* 以RequestBody方式提交
|
||||
*
|
||||
* @param api 请求的api
|
||||
* @param postParam 请求的参数
|
||||
* @param type 请求的标识
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executePostWithHeaderMore(String api, String postParam, int type, String userToken, String csrfToken, String sessionId, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPostWithHeaderMore(api, postParam, type, userToken, csrfToken, sessionId, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Post请求(带参带header)
|
||||
* 以RequestBody方式提交
|
||||
*
|
||||
* @param url 请求的全地址
|
||||
* @param postParam 请求的参数
|
||||
* String url,String postParam,String contentType,String contentLength,String timestamp,String vsopPartnerId,String vsopToken
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executePostWithShanxi(String url, String postParam, long timestamp, String vsopPartnerId, String vsopToken, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPostShanxi(url, postParam, timestamp, vsopPartnerId, vsopToken, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void executeV2Post(String api, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mV2HttpPost(api, map, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载文件
|
||||
*/
|
||||
public void executeDownFile(String url, int type, HttpRequestFileCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpDownFile(url, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
public Disposable executePostDisposable(String api, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
return mHttpRequest.mHttpPostDisposable(api, map, type, callBack);
|
||||
}
|
||||
|
||||
/**
|
||||
* Post请求(包含数组)
|
||||
*
|
||||
* @param api 请求的api
|
||||
* @param treeMap 请求的参数
|
||||
* @param data 请求的数组
|
||||
* @param type 请求的标识
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executePost(String api, TreeMap treeMap, String[] data, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpPost(api, treeMap, data, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 单文件上传
|
||||
*
|
||||
* @param api 请求的api
|
||||
* @param file 上传的文件
|
||||
* @param fileKey 上传的文件对应的key
|
||||
* @param map 请求的参数
|
||||
* @param type 请求的标识
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executeFile(String api, File file, String fileKey, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpFile(api, file, fileKey, map, type, callBack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 多文件上传
|
||||
*
|
||||
* @param api 请求的api
|
||||
* @param list 上传的文件集合
|
||||
* @param fileList 上传的文件集合对应的key
|
||||
* @param map 请求的参数
|
||||
* @param type 请求的标识
|
||||
* @param callBack 结果返回接口
|
||||
*/
|
||||
public void executeMultiFile(String api, List<File> list, List<String> fileList, TreeMap map, int type, HttpRequestCallback callBack) {
|
||||
checkMHttpRequest();
|
||||
if(null != mHttpRequest) {
|
||||
mHttpRequest.mHttpMultiFile(api, list, fileList, map, type, callBack);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 偶现mHttpRequest为空,导致空指针异常
|
||||
* */
|
||||
private void checkMHttpRequest(){
|
||||
if(mHttpRequest == null){
|
||||
LogUtils.d("check mHttpRequest is null,need set value");
|
||||
mHttpRequest = HttpRetrofitRequest.getInstances();
|
||||
HttpRetrofitRequest.getInstances().setHttpBaseUrl(BaseUrl.getSingleton().getBaseHttpUrl());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
20
libdata/src/main/java/com/migu/libnetwork/HttpsTrustManager.kt
Executable file
20
libdata/src/main/java/com/migu/libnetwork/HttpsTrustManager.kt
Executable file
@@ -0,0 +1,20 @@
|
||||
package com.migu.libnetwork
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import java.security.cert.X509Certificate
|
||||
import javax.net.ssl.X509TrustManager
|
||||
|
||||
@SuppressLint("CustomX509TrustManager")
|
||||
class HttpsTrustManager : X509TrustManager {
|
||||
@SuppressLint("TrustAllX509TrustManager")
|
||||
override fun checkClientTrusted(chain: Array<X509Certificate?>, authType: String?) {
|
||||
}
|
||||
|
||||
@SuppressLint("TrustAllX509TrustManager")
|
||||
override fun checkServerTrusted(chain: Array<X509Certificate?>, authType: String?) {
|
||||
}
|
||||
|
||||
override fun getAcceptedIssuers(): Array<X509Certificate?> {
|
||||
return arrayOfNulls(0)
|
||||
}
|
||||
}
|
||||
86
libdata/src/main/java/com/migu/libnetwork/IHttpRequest.java
Executable file
86
libdata/src/main/java/com/migu/libnetwork/IHttpRequest.java
Executable file
@@ -0,0 +1,86 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import io.reactivex.rxjava3.disposables.Disposable;
|
||||
|
||||
/**
|
||||
* content: 请求接口的方式
|
||||
*/
|
||||
public interface IHttpRequest {
|
||||
|
||||
// Get请求(使用Path形式)
|
||||
void mHttpGetPath(String url, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
// GET请求(无参)
|
||||
void mHttpGet(String api, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
// GET请求(带headers)
|
||||
void mHttpGet(String url, String headers, HttpRequestCallback mCallBack);
|
||||
|
||||
// GET请求(带headers)
|
||||
void mHttpGetLogin(String url, String headers, HttpRequestCallback mCallBack);
|
||||
// GET请求(带headers)
|
||||
void mHttpIsLogin(String url, String headers, HttpRequestCallback mCallBack);
|
||||
// GET请求(带headers)
|
||||
void mHttpGetPayResultCycle(String url, String headers,String tenant, HttpRequestCallback mCallBack);
|
||||
|
||||
// GET请求(带headers)
|
||||
void mHttpGetUserInfo(String url, String token,String header, HttpRequestCallback mCallBack);
|
||||
|
||||
//山西全地址带headers
|
||||
void mHttpPostShanxi(String url, String postParam, long timestamp, String vsopPartnerId, String vsopToken, HttpRequestCallback mCallBack);
|
||||
|
||||
// Get请求(带参)
|
||||
void mHttpGet(String api, TreeMap map, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
// Post请求(无参)
|
||||
void mHttpPost(String api, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
// Post请求(带参)
|
||||
// 以RequestBody方式提交
|
||||
void mHttpPost(String api, TreeMap map, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
// Post请求(带参)
|
||||
// 以RequestBody方式提交(超时不需要重试)
|
||||
void mHttpPostNoRetry(String api, TreeMap map, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
void mHttpPostPath(String url, TreeMap map, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
void mHttpPostPathHeader(String url, String content, String header, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
void mHttpPostPathSignHeader(String url, String content, String sign, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
void mHttpPost(String api, String postParam, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
void mHttpPostOrderList(String api, String token, String tenant, HttpRequestCallback callBack);
|
||||
void mHttpPostActivate(String api,String postParam, String tenant, HttpRequestCallback callBack);
|
||||
void mHttpPostQueryVipInfo(String api,String tenant, HttpRequestCallback callBack);
|
||||
|
||||
void mHttpPostWithHeaderToken(String api, String postParam, int type, String token, HttpRequestCallback callBack);
|
||||
|
||||
void mHttpPostWithHeaderMore(String api, String postParam, int type, String userToken, String csrfToken, String sessionId, HttpRequestCallback callBack);
|
||||
|
||||
void mHttpPostCloudLogin(String api, TreeMap map, String tenant, String signature, HttpRequestCallback callBack);
|
||||
|
||||
// Post请求(带参)
|
||||
// 以RequestBody方式提交
|
||||
void mV2HttpPost(String api, TreeMap map, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
Disposable mHttpPostDisposable(String api, TreeMap map, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
// Post请求(包含数组)
|
||||
void mHttpPost(String api, TreeMap treeMap, String[] data, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
// 单文件上传
|
||||
void mHttpFile(String api, File file, String fileKey, TreeMap map, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
// 多文件上传
|
||||
void mHttpMultiFile(String api, List<File> list, List<String> fileList, TreeMap map, int type, HttpRequestCallback mCallBack);
|
||||
|
||||
// Post请求(无参)
|
||||
void mHttpDownFile(String url, int type, HttpRequestFileCallback mCallBack);
|
||||
}
|
||||
86
libdata/src/main/java/com/migu/libnetwork/NetUtil.java
Executable file
86
libdata/src/main/java/com/migu/libnetwork/NetUtil.java
Executable file
@@ -0,0 +1,86 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.NetworkInfo;
|
||||
|
||||
import com.pukka.libcore.utils.ContextUtils;
|
||||
import com.pukka.libcore.utils.LogUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.RequestBody;
|
||||
import okio.Buffer;
|
||||
|
||||
public class NetUtil {
|
||||
public static boolean isNetwork = true;
|
||||
|
||||
/**
|
||||
* 判断是否有网络
|
||||
*
|
||||
* @return 返回值
|
||||
*/
|
||||
public static boolean isNetworkConnected() {
|
||||
if (!isNetwork) {
|
||||
return false;
|
||||
}
|
||||
Context context = ContextUtils.getApplication();
|
||||
if (context != null) {
|
||||
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
|
||||
if (mNetworkInfo != null) {
|
||||
return mNetworkInfo.isAvailable();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String printParams(RequestBody body) {
|
||||
Buffer buffer = new Buffer();
|
||||
try {
|
||||
body.writeTo(buffer);
|
||||
Charset charset = Charset.forName("UTF-8");
|
||||
MediaType contentType = body.contentType();
|
||||
if (contentType != null) {
|
||||
charset = contentType.charset(Charset.forName("UTF-8"));
|
||||
}
|
||||
String params = buffer.readString(charset);
|
||||
return params;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
public static void printHttpLog(boolean isNet, long startTime, Request request, String content) {
|
||||
String params = "";
|
||||
long endTime = System.currentTimeMillis();
|
||||
long duration = endTime - startTime;
|
||||
if (request.body() != null) {
|
||||
params = printParams(request.body());
|
||||
}
|
||||
LogUtils.onlyD("Http request", "=================================== " + (isNet ? "有网请求" : "缓存请求") + " " +
|
||||
"HTTP START===================================");
|
||||
LogUtils.longD("Http request",
|
||||
"\n| 请求地址:| " + request.url()
|
||||
+ "\n| 请求参数:| " + params
|
||||
+ "\n| 请求头:| " + request.headers()
|
||||
+ "\n| 请求耗时:| " + duration + "毫秒");
|
||||
LogUtils.longD("Http request", "请求返回:" + content);
|
||||
LogUtils.onlyD("Http request", "=================================== HTTP END " +
|
||||
"===================================");
|
||||
|
||||
// WzhLog.i("Http request","\n\n=================================== "+(isNet?"有网请求":"缓存请求")+" HTTP " +
|
||||
// "START===================================");
|
||||
// WzhLog.i("Http request",
|
||||
// "\n| 请求地址:| " + request.toString()
|
||||
// + "\n| 请求参数:| " + params
|
||||
// + "\n| 请求耗时:| " + duration + "毫秒"
|
||||
// + "\n| 请求返回:| " + content);
|
||||
// WzhLog.i("Http request","\n=================================== HTTP END ===================================\n ");
|
||||
}
|
||||
}
|
||||
83
libdata/src/main/java/com/migu/libnetwork/OkHttpClientUtil.java
Executable file
83
libdata/src/main/java/com/migu/libnetwork/OkHttpClientUtil.java
Executable file
@@ -0,0 +1,83 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
|
||||
import java.io.File;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import okhttp3.Cache;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.internal.cache.CacheInterceptor;
|
||||
|
||||
public class OkHttpClientUtil {
|
||||
|
||||
// 是否开启拦截,默认情况下开启
|
||||
private boolean mIsIntercept = true;
|
||||
// 设置数据读取超时时间
|
||||
private long mReadTimeOut = 3000;
|
||||
// 设置网络连接超时时间
|
||||
private long mConnectTimeOut = 3000;
|
||||
// 设置写入服务器的超时时间
|
||||
private long mWriteTimeOut = 3000;
|
||||
|
||||
private static volatile OkHttpClientUtil okHttpUtil;
|
||||
|
||||
static OkHttpClientUtil getOkHttpUtil() {
|
||||
if (okHttpUtil == null) {
|
||||
synchronized (OkHttpClientUtil.class) {
|
||||
if (okHttpUtil == null) {
|
||||
okHttpUtil = new OkHttpClientUtil();
|
||||
}
|
||||
}
|
||||
}
|
||||
return okHttpUtil;
|
||||
}
|
||||
|
||||
/**
|
||||
* 私有构造函数,保证全局唯一
|
||||
*/
|
||||
private OkHttpClientUtil() {
|
||||
|
||||
}
|
||||
|
||||
// 设置数据读取超时时间
|
||||
OkHttpClientUtil setTimeOutTime(long timeout) {
|
||||
mReadTimeOut = timeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
// 设置网络连接超时时间
|
||||
OkHttpClientUtil setConnectTime(long timeout) {
|
||||
mConnectTimeOut = timeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
// 设置写入服务器的超时时间
|
||||
OkHttpClientUtil setWriteTime(long timeout) {
|
||||
mWriteTimeOut = timeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
// 设置拦截器
|
||||
OkHttpClientUtil setIntercept(boolean isIntercept) {
|
||||
this.mIsIntercept = isIntercept;
|
||||
return this;
|
||||
}
|
||||
|
||||
// 设置Build方法
|
||||
public OkHttpClient build() {
|
||||
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
|
||||
okHttpClient.readTimeout(mReadTimeOut, TimeUnit.MILLISECONDS);
|
||||
okHttpClient.connectTimeout(mConnectTimeOut, TimeUnit.MILLISECONDS);
|
||||
okHttpClient.writeTimeout(mWriteTimeOut, TimeUnit.MILLISECONDS);
|
||||
okHttpClient.addInterceptor(new HttpRequestInterceptor());
|
||||
return okHttpClient.build();
|
||||
}
|
||||
|
||||
public OkHttpClient fileBuild() {
|
||||
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
|
||||
okHttpClient.readTimeout(mReadTimeOut, TimeUnit.MILLISECONDS);
|
||||
okHttpClient.connectTimeout(mConnectTimeOut, TimeUnit.MILLISECONDS);
|
||||
okHttpClient.writeTimeout(mWriteTimeOut, TimeUnit.MILLISECONDS);
|
||||
return okHttpClient.build();
|
||||
}
|
||||
}
|
||||
30
libdata/src/main/java/com/migu/libnetwork/OkHttpSsl.java
Executable file
30
libdata/src/main/java/com/migu/libnetwork/OkHttpSsl.java
Executable file
@@ -0,0 +1,30 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import com.migu.base.SSLSocketFactoryCompat;
|
||||
import com.migu.base.TrustAllHostnameVerifier;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
|
||||
/**
|
||||
* 处理证书不受信任的问题
|
||||
*/
|
||||
public class OkHttpSsl {
|
||||
//okHttp3添加信任所有证书
|
||||
public static OkHttpClient getUnsafeOkHttpClient() {
|
||||
try {
|
||||
OkHttpClient.Builder builder = new OkHttpClient.Builder();
|
||||
builder.sslSocketFactory(new SSLSocketFactoryCompat(new HttpsTrustManager())
|
||||
, new HttpsTrustManager());
|
||||
builder.addInterceptor(new HttpRequestInterceptor());
|
||||
builder.hostnameVerifier(new TrustAllHostnameVerifier());//忽略ssl
|
||||
return builder.connectTimeout(10, TimeUnit.SECONDS)
|
||||
.writeTimeout(10, TimeUnit.SECONDS)
|
||||
.readTimeout(10, TimeUnit.SECONDS)
|
||||
.build();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
169
libdata/src/main/java/com/migu/libnetwork/RetrofitClientUtil.java
Executable file
169
libdata/src/main/java/com/migu/libnetwork/RetrofitClientUtil.java
Executable file
@@ -0,0 +1,169 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.pukka.libcore.base.BaseUrl;
|
||||
import com.pukka.libcore.utils.LogUtils;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
import retrofit2.CallAdapter;
|
||||
import retrofit2.Converter;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
|
||||
import retrofit2.converter.scalars.ScalarsConverterFactory;
|
||||
|
||||
/**
|
||||
* content: 对Retrofit进行封装
|
||||
*/
|
||||
public class RetrofitClientUtil {
|
||||
private static final String TAG = "RetrofitClientUtil ";
|
||||
// 网络请求的baseUrl
|
||||
private String mBaseUrl;
|
||||
// 设置数据解析器
|
||||
private Converter.Factory mBaseFactory;
|
||||
// 新增数据解析器
|
||||
private Converter.Factory mAddFactory;
|
||||
// 设置网络请求适配器
|
||||
private CallAdapter.Factory mCallFactory;
|
||||
// 设置OkHttpClient
|
||||
private OkHttpClient mOkHttpClient;
|
||||
|
||||
private String V2baseUrl;
|
||||
|
||||
private static volatile RetrofitClientUtil retrofitUtil;
|
||||
|
||||
public static RetrofitClientUtil getRetrofitUtil() {
|
||||
if (retrofitUtil == null) {
|
||||
synchronized (RetrofitClientUtil.class) {
|
||||
if (retrofitUtil == null) {
|
||||
retrofitUtil = new RetrofitClientUtil();
|
||||
}
|
||||
}
|
||||
}
|
||||
return retrofitUtil;
|
||||
}
|
||||
|
||||
|
||||
public String getmBaseUrl(){
|
||||
return mBaseUrl;
|
||||
}
|
||||
|
||||
private RetrofitClientUtil() {
|
||||
mBaseUrl = HttpRequestConstants.BASE_URL;
|
||||
LogUtils.d(TAG + "RetrofitClientUtil", mBaseUrl);
|
||||
// 默认基础数据类型的解析
|
||||
mBaseFactory = ScalarsConverterFactory.create();
|
||||
// RxJava来处理Call返回值
|
||||
mCallFactory = RxJava3CallAdapterFactory.create();
|
||||
}
|
||||
|
||||
// 设置BaseUrl
|
||||
public void setBaseUrl(String baseUrl) {
|
||||
if (TextUtils.isEmpty(baseUrl)) {
|
||||
return;
|
||||
}
|
||||
HttpRequestConstants.BASE_URL = baseUrl;
|
||||
this.mBaseUrl = baseUrl;
|
||||
LogUtils.d(TAG + "setBaseUrl", mBaseUrl);
|
||||
}
|
||||
|
||||
public String getV2baseUrl() {
|
||||
return V2baseUrl;
|
||||
}
|
||||
|
||||
// 设置数据解析
|
||||
public RetrofitClientUtil addConverterFactory(Converter.Factory factory) {
|
||||
this.mAddFactory = factory;
|
||||
return this;
|
||||
}
|
||||
|
||||
// 设置网络请求适配器
|
||||
public RetrofitClientUtil addCallAdapterFactory(CallAdapter.Factory factory) {
|
||||
this.mCallFactory = factory;
|
||||
return this;
|
||||
}
|
||||
|
||||
// 设置写入服务器的超时时间
|
||||
public RetrofitClientUtil setOkHttpClient(OkHttpClient okHttpClient) {
|
||||
this.mOkHttpClient = okHttpClient;
|
||||
return this;
|
||||
}
|
||||
|
||||
// 设置Build方法
|
||||
public Retrofit build() {
|
||||
LogUtils.d(TAG + "build", mBaseUrl);
|
||||
Retrofit.Builder builder = new Retrofit.Builder();
|
||||
builder.baseUrl(mBaseUrl);
|
||||
builder.addConverterFactory(mBaseFactory);
|
||||
if (mAddFactory != null) {
|
||||
builder.addConverterFactory(mAddFactory);
|
||||
}
|
||||
builder.addCallAdapterFactory(mCallFactory);
|
||||
builder.client(mOkHttpClient);
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
// public Retrofit noBaseurlBuild() {
|
||||
// Retrofit.Builder builder = new Retrofit.Builder();
|
||||
// String v2BaseUrl = changeV2BaseUrl();
|
||||
// V2baseUrl = v2BaseUrl;
|
||||
// LogUtils.d("noBaseurlBuild: " + v2BaseUrl);
|
||||
// builder.baseUrl(v2BaseUrl);
|
||||
// builder.addConverterFactory(mBaseFactory);
|
||||
// if (mAddFactory != null) {
|
||||
// builder.addConverterFactory(mAddFactory);
|
||||
// }
|
||||
// builder.addCallAdapterFactory(mCallFactory);
|
||||
// builder.client(mOkHttpClient);
|
||||
// return builder.build();
|
||||
// }
|
||||
|
||||
// private String changeV2BaseUrl() {
|
||||
// String v2BaseUrl = "http://36.155.98.95:18082";
|
||||
// BaseUrl singleton = BaseUrl.getSingleton();
|
||||
// String baseUrlState = singleton.getBaseUrlState();
|
||||
// if ("debug".equals(baseUrlState)) {
|
||||
// if (HttpInterface.isHttps) {
|
||||
// v2BaseUrl = "http://36.155.98.104:15310";
|
||||
// } else {
|
||||
// v2BaseUrl = "http://36.155.98.104:15310";
|
||||
// }
|
||||
// } else if ("preview".equals(baseUrlState) || singleton.buildType.equals("0")) {
|
||||
// if (HttpInterface.isHttps) {
|
||||
// v2BaseUrl = "https://36.155.98.94:18081";
|
||||
// } else {
|
||||
// v2BaseUrl = "http://36.155.98.95:18082";
|
||||
// }
|
||||
// } else if ("release".equals(baseUrlState) || singleton.buildType.equals("1")) {
|
||||
// if (HttpInterface.isHttps) {
|
||||
// v2BaseUrl = "https://dpmh-gateway.itv.cmvideo.cn:8443";
|
||||
// } else {
|
||||
// v2BaseUrl = "http://dpmh-gateway.itv.cmvideo.cn:8090";
|
||||
// }
|
||||
// } else {
|
||||
// if ("preview".equals(com.migu.libcore.BuildConfig.BUILD_TYPE)) {
|
||||
// if (HttpInterface.isHttps) {
|
||||
// v2BaseUrl = "https://36.155.98.94:18081";
|
||||
// } else {
|
||||
// v2BaseUrl = "http://36.155.98.95:18082";
|
||||
// }
|
||||
// } else if ("debug".equals(com.migu.libcore.BuildConfig.BUILD_TYPE)) {
|
||||
// if (HttpInterface.isHttps) {
|
||||
// v2BaseUrl = "http://36.155.98.104:15310";
|
||||
// } else {
|
||||
// v2BaseUrl = "http://36.155.98.104:15310";
|
||||
// }
|
||||
// } else {
|
||||
// if (HttpInterface.isHttps) {
|
||||
// v2BaseUrl = "https://dpmh-gateway.itv.cmvideo.cn:8443";
|
||||
// } else {
|
||||
// v2BaseUrl = "http://dpmh-gateway.itv.cmvideo.cn:8090";
|
||||
// }
|
||||
//
|
||||
// }
|
||||
// }
|
||||
// LogUtils.d("noBaseurlBuild1: " + v2BaseUrl + " HttpInterface.isHttps: " + HttpInterface.isHttps);
|
||||
// return v2BaseUrl;
|
||||
// }
|
||||
|
||||
}
|
||||
97
libdata/src/main/java/com/migu/libnetwork/RetryFunction.java
Executable file
97
libdata/src/main/java/com/migu/libnetwork/RetryFunction.java
Executable file
@@ -0,0 +1,97 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import com.pukka.libcore.utils.LogUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import io.reactivex.rxjava3.core.Observable;
|
||||
import io.reactivex.rxjava3.core.ObservableSource;
|
||||
import io.reactivex.rxjava3.functions.Function;
|
||||
|
||||
/**
|
||||
* content: 设置重新连接
|
||||
*/
|
||||
public class RetryFunction implements Function<Observable<Throwable>, ObservableSource<?>> {
|
||||
|
||||
/**
|
||||
* 可重试次数
|
||||
*/
|
||||
private int maxConnectCount = 3;
|
||||
|
||||
/**
|
||||
* 当前已重试次数
|
||||
*/
|
||||
private int currentRetryCount = 0;
|
||||
|
||||
/**
|
||||
* 重试等待时间
|
||||
*/
|
||||
private int waitRetryTime = 0;
|
||||
|
||||
/**
|
||||
* 接口请求地址
|
||||
*/
|
||||
private String requestUrl;
|
||||
|
||||
public RetryFunction(String requestUrl) {
|
||||
this.requestUrl = requestUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ObservableSource<?> apply(Observable<Throwable> throwableObservable) throws Throwable {
|
||||
// 参数Observable<Throwable>中的泛型 = 上游操作符抛出的异常,可通过该条件来判断异常的类型
|
||||
return throwableObservable.flatMap(new Function<Throwable, ObservableSource<?>>() {
|
||||
@Override
|
||||
public ObservableSource<?> apply(@NonNull Throwable throwable) throws Exception {
|
||||
|
||||
// 输出异常信息
|
||||
LogUtils.e(HttpRequestConstants.TAG, requestUrl + " 接口发生异常 = " + throwable.toString());
|
||||
|
||||
/**
|
||||
* 需求1:根据异常类型选择是否重试
|
||||
* 即,当发生的异常 = 网络异常 = IO异常 才选择重试
|
||||
*/
|
||||
if (throwable instanceof IOException) {
|
||||
LogUtils.e(HttpRequestConstants.TAG, "属于IO异常,需重试");
|
||||
|
||||
/**
|
||||
* 需求2:限制重试次数
|
||||
* 即,当已重试次数 < 设置的重试次数,才选择重试
|
||||
*/
|
||||
if (currentRetryCount < maxConnectCount) {
|
||||
|
||||
// 记录重试次数
|
||||
currentRetryCount++;
|
||||
LogUtils.e(HttpRequestConstants.TAG, "重试次数 = " + currentRetryCount);
|
||||
|
||||
/**
|
||||
* 需求2:实现重试
|
||||
* 通过返回的Observable发送的事件 = Next事件,从而使得retryWhen()重订阅,最终实现重试功能
|
||||
*
|
||||
* 需求3:延迟1段时间再重试
|
||||
* 采用delay操作符 = 延迟一段时间发送,以实现重试间隔设置
|
||||
*
|
||||
* 需求4:遇到的异常越多,时间越长
|
||||
* 在delay操作符的等待时间内设置 = 每重试1次,增多延迟重试时间1s
|
||||
*/
|
||||
// 设置等待时间
|
||||
waitRetryTime = 1000 + currentRetryCount * 1000;
|
||||
LogUtils.e(HttpRequestConstants.TAG, "等待时间 =" + waitRetryTime);
|
||||
return Observable.just(1).delay(waitRetryTime, TimeUnit.MILLISECONDS);
|
||||
} else {
|
||||
// 若重试次数已 > 设置重试次数,则不重试
|
||||
// 通过发送error来停止重试(可在观察者的onError()中获取信息)
|
||||
return Observable.error(new Throwable("网络异常,重试次数已超过设置次数 = " + currentRetryCount + ",即 不再重试"));
|
||||
}
|
||||
}
|
||||
// 若发生的异常不属于I/O异常,则不重试
|
||||
// 通过返回的Observable发送的事件 = Error事件 实现(可在观察者的onError()中获取信息)
|
||||
else {
|
||||
return Observable.error(new Throwable("发生了非网络异常 "+ throwable.getClass().getSimpleName() +"|"+throwable.getMessage() ));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
181
libdata/src/main/java/com/migu/libnetwork/RxJavaFileObserver.java
Executable file
181
libdata/src/main/java/com/migu/libnetwork/RxJavaFileObserver.java
Executable file
@@ -0,0 +1,181 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Environment;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
|
||||
import com.pukka.libcore.utils.ContextUtils;
|
||||
import com.pukka.libcore.utils.LogUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import io.reactivex.rxjava3.core.Observer;
|
||||
import io.reactivex.rxjava3.disposables.Disposable;
|
||||
import okhttp3.ResponseBody;
|
||||
|
||||
/**
|
||||
* content: 处理接口返回的请求结果
|
||||
*/
|
||||
public class RxJavaFileObserver implements Observer<ResponseBody> {
|
||||
|
||||
private final HttpRequestFileCallback mFileCallBack;
|
||||
private static final String TAG = "RxJavaFileObserver";
|
||||
private final int mType;
|
||||
private final Context mContext;
|
||||
private Disposable disposable;
|
||||
private String destDir;
|
||||
//private String fileName = "pukkaweb.apk";
|
||||
private String fileName = "pukkaweb"+System.currentTimeMillis()+".apk";
|
||||
RxJavaFileObserver(int type, HttpRequestFileCallback mFileCallBack) {
|
||||
this.mFileCallBack = mFileCallBack;
|
||||
this.mContext = ContextUtils.getContext();
|
||||
this.mType = type;
|
||||
if (null != mContext) {
|
||||
if (mContext.getExternalCacheDir() != null) {
|
||||
destDir = mContext.getExternalCacheDir() + "/jiecheng/";
|
||||
} else if(null != mContext.getExternalFilesDir("")) {
|
||||
destDir = mContext.getExternalFilesDir("") + "/jiecheng/";
|
||||
}else{
|
||||
destDir = Environment.getExternalStorageDirectory() + "/jiecheng/";
|
||||
}
|
||||
}
|
||||
LogUtils.d(TAG, "destDir mContext:" + mContext);
|
||||
LogUtils.d(TAG, "destDir:" + destDir);
|
||||
LogUtils.d(TAG, "destDir getFilesDir:" + mContext.getFilesDir());
|
||||
LogUtils.d(TAG, "destDir getCacheDir:" + mContext.getCacheDir());
|
||||
LogUtils.d(TAG, "destDir getExternalFilesDir:" + mContext.getExternalFilesDir(""));
|
||||
LogUtils.d(TAG, "destDir getExternalCacheDir:" + mContext.getExternalCacheDir());
|
||||
}
|
||||
|
||||
RxJavaFileObserver(Context context, int type, String fileName, HttpRequestFileCallback mFileCallBack) {
|
||||
this.mFileCallBack = mFileCallBack;
|
||||
this.mContext = context;
|
||||
this.mType = type;
|
||||
if (mContext.getExternalCacheDir() != null) {
|
||||
destDir = mContext.getExternalCacheDir() + "/jiecheng/";
|
||||
} else {
|
||||
destDir = mContext.getExternalFilesDir("") + "/jiecheng/";
|
||||
}
|
||||
LogUtils.d(TAG, "destDir mContext:" + mContext);
|
||||
LogUtils.d(TAG, "destDir:" + destDir);
|
||||
LogUtils.d(TAG, "destDir getFilesDir:" + mContext.getFilesDir());
|
||||
LogUtils.d(TAG, "destDir getCacheDir:" + mContext.getCacheDir());
|
||||
LogUtils.d(TAG, "destDir getExternalFilesDir:" + mContext.getExternalFilesDir(""));
|
||||
LogUtils.d(TAG, "destDir getExternalCacheDir:" + mContext.getExternalCacheDir());
|
||||
|
||||
this.fileName = fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
disposable = d;
|
||||
}
|
||||
|
||||
public Disposable getDisposable() {
|
||||
return disposable;
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口请求成功
|
||||
*/
|
||||
@Override
|
||||
public void onNext(@NonNull ResponseBody responseBody) {
|
||||
LogUtils.d(TAG, "responseBody.contentLength()" + responseBody.contentLength());
|
||||
try {
|
||||
saveFile(responseBody, destDir, fileName);
|
||||
} catch (IOException e) {
|
||||
LogUtils.d(TAG, "onError onNext");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口请求失败
|
||||
*/
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
LogUtils.d(TAG, "onError");
|
||||
// 1.检查网络设置
|
||||
if (!HttpTool.hasNetwork()) {
|
||||
onComplete();
|
||||
mFileCallBack.onRequestNetFail(mType);
|
||||
return;
|
||||
}
|
||||
// 2.非网络错误,接口请求错误
|
||||
mFileCallBack.onRequestFail(e.getMessage(), "0000", mType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口请求完成
|
||||
*/
|
||||
@Override
|
||||
public void onComplete() {
|
||||
LogUtils.d(TAG, "onComplete");
|
||||
}
|
||||
|
||||
/**
|
||||
* 将文件写入本地
|
||||
*
|
||||
* @param responseBody 请求结果全体
|
||||
* @param destFileDir 目标文件夹
|
||||
* @param destFileName 目标文件名
|
||||
* @return 写入完成的文件
|
||||
* @throws IOException IO异常
|
||||
*/
|
||||
private void saveFile(ResponseBody responseBody, String destFileDir, String destFileName) throws IOException {
|
||||
InputStream is = null;
|
||||
byte[] buf = new byte[2048];
|
||||
int len;
|
||||
FileOutputStream fos = null;
|
||||
try {
|
||||
is = responseBody.byteStream();
|
||||
final long total = responseBody.contentLength();
|
||||
long sum = 0;
|
||||
|
||||
File dir = new File(destFileDir);
|
||||
if (!dir.exists()) {
|
||||
dir.mkdirs();
|
||||
}
|
||||
mFileCallBack.onStart();
|
||||
File file = new File(dir, destFileName);
|
||||
LogUtils.d(TAG, "filePath:" + file.getPath());
|
||||
fos = new FileOutputStream(file);
|
||||
int progress = 0;
|
||||
while ((len = is.read(buf)) != -1) {
|
||||
sum += len;
|
||||
fos.write(buf, 0, len);
|
||||
final long finalSum = sum;
|
||||
if (progress != (int) (finalSum * 100 / total)) {
|
||||
progress = (int) (finalSum * 100 / total);
|
||||
LogUtils.d(TAG, "responseLength onProgress" + progress + "...");
|
||||
mFileCallBack.onProgress((int) progress);
|
||||
if (progress == 100) {
|
||||
// 下载完成
|
||||
mFileCallBack.onComplete(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
fos.flush();
|
||||
}catch (Exception e){
|
||||
LogUtils.d(TAG, "onError saveFile");
|
||||
mFileCallBack.downFail();
|
||||
e.printStackTrace();
|
||||
}finally {
|
||||
try {
|
||||
if (is != null) {
|
||||
is.close();
|
||||
}
|
||||
if (fos != null) {
|
||||
fos.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
71
libdata/src/main/java/com/migu/libnetwork/RxJavaObserver.java
Executable file
71
libdata/src/main/java/com/migu/libnetwork/RxJavaObserver.java
Executable file
@@ -0,0 +1,71 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import com.pukka.libcore.utils.LogUtils;
|
||||
import io.reactivex.rxjava3.core.Observer;
|
||||
import io.reactivex.rxjava3.disposables.Disposable;
|
||||
|
||||
/**
|
||||
* content: 处理接口返回的请求结果
|
||||
*/
|
||||
public class RxJavaObserver implements Observer<String> {
|
||||
|
||||
private final HttpRequestCallback mCallBack;
|
||||
private final int mType;
|
||||
private Disposable disposable;
|
||||
|
||||
RxJavaObserver(int type, HttpRequestCallback callBack) {
|
||||
this.mCallBack = callBack;
|
||||
this.mType = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
disposable = d;
|
||||
}
|
||||
|
||||
public Disposable getDisposable() {
|
||||
return disposable;
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口请求成功
|
||||
*/
|
||||
@Override
|
||||
public void onNext(@NonNull String s) {
|
||||
try {
|
||||
if (HttpTool.isJsonObject(s)) {
|
||||
mCallBack.onRequestSuccess(s, mType);
|
||||
} else {
|
||||
mCallBack.onRequestSuccess(s, mType);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口请求失败
|
||||
*/
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
// 1.检查网络设置
|
||||
if (!HttpTool.hasNetwork()) {
|
||||
onComplete();
|
||||
mCallBack.onRequestNetFail(mType);
|
||||
LogUtils.e("onRequestNetFail: not have network");
|
||||
return;
|
||||
}
|
||||
// 2.非网络错误,接口请求错误
|
||||
mCallBack.onRequestFail(e.getMessage(), e.getMessage(), mType);
|
||||
LogUtils.e("onRequestNetFail: "+e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口请求完成
|
||||
*/
|
||||
@Override
|
||||
public void onComplete() {
|
||||
|
||||
}
|
||||
}
|
||||
147
libdata/src/main/java/com/migu/libnetwork/SSLSocketFactoryCompat.kt
Executable file
147
libdata/src/main/java/com/migu/libnetwork/SSLSocketFactoryCompat.kt
Executable file
@@ -0,0 +1,147 @@
|
||||
package com.migu.base
|
||||
|
||||
import android.os.Build
|
||||
import java.io.IOException
|
||||
import java.net.InetAddress
|
||||
import java.net.Socket
|
||||
import java.net.UnknownHostException
|
||||
import java.security.GeneralSecurityException
|
||||
import java.util.*
|
||||
import javax.net.ssl.SSLContext
|
||||
import javax.net.ssl.SSLSocket
|
||||
import javax.net.ssl.SSLSocketFactory
|
||||
import javax.net.ssl.X509TrustManager
|
||||
|
||||
class SSLSocketFactoryCompat// The system has no TLS. Just give up.
|
||||
(tm: X509TrustManager?) : SSLSocketFactory() {
|
||||
|
||||
private var defaultFactory: SSLSocketFactory? = null
|
||||
|
||||
companion object {
|
||||
var protocols: Array<String>? = null
|
||||
var cipherSuites: Array<String>? = null
|
||||
|
||||
init {
|
||||
try {
|
||||
val socket = getDefault().createSocket() as SSLSocket
|
||||
val protocols: LinkedList<String> = LinkedList()
|
||||
for (protocol in socket.supportedProtocols) {
|
||||
if (!protocol.uppercase(Locale.ROOT).contains("SSL")) {
|
||||
protocols.add(protocol)
|
||||
}
|
||||
}
|
||||
SSLSocketFactoryCompat.protocols = protocols.toArray(arrayOfNulls(protocols.size))
|
||||
/* set up reasonable cipher suites */
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
|
||||
// choose known secure cipher suites
|
||||
val allowedCiphers = arrayOf(// TLS 1.2
|
||||
"TLS_RSA_WITH_AES_256_GCM_SHA384",
|
||||
"TLS_RSA_WITH_AES_128_GCM_SHA256",
|
||||
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
|
||||
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
|
||||
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
|
||||
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
|
||||
"TLS_ECHDE_RSA_WITH_AES_128_GCM_SHA256",
|
||||
// maximum interoperability
|
||||
"TLS_RSA_WITH_3DES_EDE_CBC_SHA",
|
||||
"TLS_RSA_WITH_AES_128_CBC_SHA",
|
||||
// additionally
|
||||
"TLS_RSA_WITH_AES_256_CBC_SHA",
|
||||
"TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
|
||||
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
|
||||
"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
|
||||
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
|
||||
)
|
||||
val availableCiphers: Array<String> = socket.supportedCipherSuites
|
||||
val preferredCiphers = hashSetOf<String>()
|
||||
preferredCiphers.addAll(allowedCiphers)
|
||||
preferredCiphers.retainAll(availableCiphers)
|
||||
preferredCiphers.addAll(socket.enabledCipherSuites)
|
||||
cipherSuites =
|
||||
preferredCiphers.toArray(arrayOfNulls(preferredCiphers.size))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
try {
|
||||
val sslContext = SSLContext.getInstance("TLS")
|
||||
sslContext.init(null, if (tm != null) arrayOf(tm) else null, null)
|
||||
defaultFactory = sslContext.socketFactory
|
||||
} catch (e: GeneralSecurityException) {
|
||||
throw AssertionError() // The system has no TLS. Just give up.
|
||||
}
|
||||
}
|
||||
|
||||
private fun upgradeTLS(ssl: SSLSocket) {
|
||||
// Android 5.0+ (API level21) provides reasonable default settings
|
||||
// but it still allows SSLv3
|
||||
if (protocols != null) {
|
||||
ssl.enabledProtocols = protocols
|
||||
}
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && cipherSuites != null) {
|
||||
ssl.enabledCipherSuites = cipherSuites
|
||||
}
|
||||
}
|
||||
|
||||
override fun getDefaultCipherSuites(): Array<String> {
|
||||
return cipherSuites!!
|
||||
}
|
||||
|
||||
override fun getSupportedCipherSuites(): Array<String> {
|
||||
return cipherSuites!!
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
override fun createSocket(s: Socket, host: String, port: Int, autoClose: Boolean): Socket {
|
||||
val ssl = defaultFactory?.createSocket(s, host, port, autoClose)
|
||||
if (ssl is SSLSocket)
|
||||
upgradeTLS(ssl)
|
||||
return ssl!!
|
||||
}
|
||||
|
||||
@Throws(IOException::class, UnknownHostException::class)
|
||||
override fun createSocket(host: String, port: Int): Socket {
|
||||
val ssl = defaultFactory?.createSocket(host, port)
|
||||
if (ssl is SSLSocket)
|
||||
upgradeTLS(ssl)
|
||||
return ssl!!
|
||||
}
|
||||
|
||||
@Throws(IOException::class, UnknownHostException::class)
|
||||
override fun createSocket(
|
||||
host: String,
|
||||
port: Int,
|
||||
localHost: InetAddress,
|
||||
localPort: Int
|
||||
): Socket {
|
||||
val ssl = defaultFactory?.createSocket(host, port, localHost, localPort)
|
||||
if (ssl is SSLSocket)
|
||||
upgradeTLS(ssl)
|
||||
return ssl!!
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
override fun createSocket(host: InetAddress, port: Int): Socket {
|
||||
val ssl = defaultFactory?.createSocket(host, port)
|
||||
if (ssl is SSLSocket)
|
||||
upgradeTLS(ssl)
|
||||
return ssl!!
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
override fun createSocket(
|
||||
address: InetAddress,
|
||||
port: Int,
|
||||
localAddress: InetAddress,
|
||||
localPort: Int
|
||||
): Socket {
|
||||
val ssl = defaultFactory?.createSocket(address, port, localAddress, localPort)
|
||||
if (ssl is SSLSocket)
|
||||
upgradeTLS(ssl)
|
||||
return ssl!!
|
||||
}
|
||||
}
|
||||
39
libdata/src/main/java/com/migu/libnetwork/SearchApi.java
Executable file
39
libdata/src/main/java/com/migu/libnetwork/SearchApi.java
Executable file
@@ -0,0 +1,39 @@
|
||||
package com.migu.libnetwork;
|
||||
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.ResponseBody;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.Body;
|
||||
import retrofit2.http.POST;
|
||||
|
||||
|
||||
public interface SearchApi {
|
||||
|
||||
@POST("getSuggest")
|
||||
Call<ResponseBody> getSuggest(@Body RequestBody body);
|
||||
|
||||
@POST("passSwitchAES.do")
|
||||
Call<ResponseBody> getPassSwitch(@Body RequestBody body);
|
||||
@POST("goldMain")
|
||||
Call<ResponseBody> getGoldMain(@Body RequestBody body);
|
||||
|
||||
@POST("shortVideoList")
|
||||
Call<ResponseBody> getShortVideoList(@Body RequestBody body);
|
||||
|
||||
@POST("content/getsystem.do")
|
||||
Call<ResponseBody> getSystemData(@Body RequestBody body);
|
||||
|
||||
@POST("search/epgAreaConfig.do")
|
||||
Call<ResponseBody> epgAreaConfig(@Body RequestBody body);
|
||||
|
||||
// @POST("getVideoResult")
|
||||
// Call<ResponseBody> getVideoResult(@Body RequestBody body);
|
||||
//
|
||||
// @POST("getcontentlist.do")
|
||||
// Call<ResponseBody> getcontentlist(@Body RequestBody body);
|
||||
//
|
||||
// @POST("getcontentlist.do")
|
||||
// @FormUrlEncoded
|
||||
// Call<ResponseBody> getcontentlist(@Url String url, @FieldMap Map<String,String> map);
|
||||
|
||||
}
|
||||
10
libdata/src/main/java/com/migu/libnetwork/TrustAllHostnameVerifier.kt
Executable file
10
libdata/src/main/java/com/migu/libnetwork/TrustAllHostnameVerifier.kt
Executable file
@@ -0,0 +1,10 @@
|
||||
package com.migu.base
|
||||
|
||||
import javax.net.ssl.HostnameVerifier
|
||||
import javax.net.ssl.SSLSession
|
||||
|
||||
class TrustAllHostnameVerifier : HostnameVerifier {
|
||||
override fun verify(hostname: String?, session: SSLSession?): Boolean {
|
||||
return true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user