Skip to content

Commit

Permalink
优化框架类名命名、变量命名、包结构
Browse files Browse the repository at this point in the history
优化 getGenericType 方法中的代码实现
优化默认日志打印策略日志分割打印的长度
新增 EasyHttp 请求缓存实现代码示例
  • Loading branch information
getActivity committed Aug 27, 2023
1 parent fbf341a commit af97154
Show file tree
Hide file tree
Showing 21 changed files with 240 additions and 163 deletions.
7 changes: 4 additions & 3 deletions HelpDoc.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@
#### Http 明文请求

* **Android 9.0** 限制了明文流量的网络请求,非加密的流量请求都会被系统禁止掉。
如果当前应用的请求是 http 请求,而非 https ,这样就会导系统禁止当前应用进行该请求,如果 WebView 的 url 用 http 协议,同样会出现加载失败,https 不受影响

* 如果当前应用的请求是 http 请求,而非 https,这样就会导系统禁止当前应用进行该请求,如果 WebView 的 url 用 http 协议,同样会出现加载失败,https 不受影响

* 在 res 下新建一个 xml 目录,然后创建一个名为:`network_security_config.xml` 文件 ,该文件内容如下

Expand All @@ -139,7 +140,7 @@
</network-security-config>
```

* 然后在 AndroidManifest.xml application 标签内应用上面的xml配置
* 然后在 AndroidManifest.xml application 标签内应用上面的 xml 配置

```xml
<application
Expand Down Expand Up @@ -1136,7 +1137,7 @@ EasyConfig.getInstance().setLogEnabled(false);

#### 如何修改日志打印策略

* 可以先定义一个类实现 [IHttpLogStrategy](library/src/main/java/com/hjq/http/config/IHttpLogStrategy.java) 接口,然后在框架初始化的时候传入即可
* 可以先定义一个类实现 [IRequestLogStrategy](library/src/main/java/com/hjq/http/config/IRequestLogStrategy.java) 接口,然后在框架初始化的时候传入即可

```java
EasyConfig.with(okHttpClient)
Expand Down
20 changes: 16 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

* 博客地址:[网络请求,如斯优雅](https://www.jianshu.com/p/93cd59dec002)

* 可以扫码下载 Demo 进行演示或者测试,如果扫码下载不了的,[点击此处下载Demo](https://github.com/getActivity/EasyHttp/releases/download/12.0/EasyHttp.apk)
* 可以扫码下载 Demo 进行演示或者测试,如果扫码下载不了的,[点击此处下载Demo](https://github.com/getActivity/EasyHttp/releases/download/12.2/EasyHttp.apk)

![](picture/demo_code.png)

Expand Down Expand Up @@ -61,7 +61,7 @@ android {
dependencies {
// 网络请求框架:https://github.com/getActivity/EasyHttp
implementation 'com.github.getActivity:EasyHttp:12.0'
implementation 'com.github.getActivity:EasyHttp:12.2'
// OkHttp 框架:https://github.com/square/okhttp
// noinspection GradleDependency
implementation 'com.squareup.okhttp3:okhttp:3.12.13'
Expand All @@ -70,13 +70,21 @@ dependencies {

* 需要注意的是:由于使用了 Lifecycle 特性,目前框架只支持 AndroidX 的项目集成

#### 框架混淆规则

* 在混淆规则文件 `proguard-rules.pro` 中加入

```text
-keep class com.hjq.http.** {*;}
```

## [框架的具体用法请点击这里查看](HelpDoc.md)

### 不同网络请求框架之间的对比

| 功能或细节 | [EasyHttp](https://github.com/getActivity/EasyHttp) | [Retrofit](https://github.com/square/retrofit) | [OkGo](https://github.com/jeasonlzy/okhttp-OkGo) |
| :----: | :------: | :-----: | :-----: |
| 对应版本 | 12.0 | 2.9.0 | 3.0.4 |
| 对应版本 | 12.2 | 2.9.0 | 3.0.4 |
| issues 数 | [![](https://img.shields.io/github/issues/getActivity/EasyHttp.svg)](https://github.com/getActivity/EasyHttp/issues) | [![](https://img.shields.io/github/issues/square/retrofit.svg)](https://github.com/square/retrofit/issues) | [![](https://img.shields.io/github/issues/jeasonlzy/okhttp-OkGo.svg)](https://github.com/jeasonlzy/okhttp-OkGo/issues) |
| **aar 包大小** | 90 KB | 123 KB | 131 KB |
| minSdk 要求 | API 14+ | API 21+ | API 14+ |
Expand Down Expand Up @@ -229,14 +237,18 @@ EasyHttp.post(this)

* 悬浮窗框架:[EasyWindow](https://github.com/getActivity/EasyWindow) ![](https://img.shields.io/github/stars/getActivity/EasyWindow.svg) ![](https://img.shields.io/github/forks/getActivity/EasyWindow.svg)

* Shape 框架:[ShapeView](https://github.com/getActivity/ShapeView) ![](https://img.shields.io/github/stars/getActivity/ShapeView.svg) ![](https://img.shields.io/github/forks/getActivity/ShapeView.svg)
* ShapeView 框架:[ShapeView](https://github.com/getActivity/ShapeView) ![](https://img.shields.io/github/stars/getActivity/ShapeView.svg) ![](https://img.shields.io/github/forks/getActivity/ShapeView.svg)

* ShapeDrawable 框架:[ShapeDrawable](https://github.com/getActivity/ShapeDrawable) ![](https://img.shields.io/github/stars/getActivity/ShapeDrawable.svg) ![](https://img.shields.io/github/forks/getActivity/ShapeDrawable.svg)

* 语种切换框架:[MultiLanguages](https://github.com/getActivity/MultiLanguages) ![](https://img.shields.io/github/stars/getActivity/MultiLanguages.svg) ![](https://img.shields.io/github/forks/getActivity/MultiLanguages.svg)

* Gson 解析容错:[GsonFactory](https://github.com/getActivity/GsonFactory) ![](https://img.shields.io/github/stars/getActivity/GsonFactory.svg) ![](https://img.shields.io/github/forks/getActivity/GsonFactory.svg)

* 日志查看框架:[Logcat](https://github.com/getActivity/Logcat) ![](https://img.shields.io/github/stars/getActivity/Logcat.svg) ![](https://img.shields.io/github/forks/getActivity/Logcat.svg)

* 嵌套滚动布局框架:[NestedScrollLayout](https://github.com/getActivity/NestedScrollLayout) ![](https://img.shields.io/github/stars/getActivity/NestedScrollLayout.svg) ![](https://img.shields.io/github/forks/getActivity/NestedScrollLayout.svg)

* Android 版本适配:[AndroidVersionAdapter](https://github.com/getActivity/AndroidVersionAdapter) ![](https://img.shields.io/github/stars/getActivity/AndroidVersionAdapter.svg) ![](https://img.shields.io/github/forks/getActivity/AndroidVersionAdapter.svg)

* Android 代码规范:[AndroidCodeStandard](https://github.com/getActivity/AndroidCodeStandard) ![](https://img.shields.io/github/stars/getActivity/AndroidCodeStandard.svg) ![](https://img.shields.io/github/forks/getActivity/AndroidCodeStandard.svg)
Expand Down
14 changes: 7 additions & 7 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ android {
applicationId 'com.hjq.easy.demo'
minSdkVersion 21
targetSdkVersion 31
versionCode 1200
versionName '12.0'
versionCode 1202
versionName '12.2'
}

// 支持 JDK 1.8
Expand Down Expand Up @@ -73,28 +73,28 @@ dependencies {
implementation 'com.squareup.okhttp3:okhttp:3.12.13'

// 吐司框架:https://github.com/getActivity/Toaster
implementation 'com.github.getActivity:Toaster:12.2'
implementation 'com.github.getActivity:Toaster:12.3'

// 权限请求框架:https://github.com/getActivity/XXPermissions
implementation 'com.github.getActivity:XXPermissions:18.2'
implementation 'com.github.getActivity:XXPermissions:18.3'

// 标题栏框架:https://github.com/getActivity/TitleBar
implementation 'com.github.getActivity:TitleBar:10.5'

// Json 解析框架:https://github.com/google/gson
implementation 'com.google.code.gson:gson:2.10.1'
// Gson 解析容错:https://github.com/getActivity/GsonFactory
implementation 'com.github.getActivity:GsonFactory:6.5'
implementation 'com.github.getActivity:GsonFactory:8.0'

// 腾讯 MMKV:https://github.com/Tencent/MMKV
implementation 'com.tencent:mmkv-static:1.2.14'

// 日志调试框架:https://github.com/getActivity/Logcat
debugImplementation 'com.github.getActivity:Logcat:11.2'
debugImplementation 'com.github.getActivity:Logcat:11.8'

// OkHttp 抓包框架:https://github.com/lygttpod/AndroidMonitor
// debugImplementation 'io.github.lygttpod:monitor:0.0.7'

// 内存泄漏监测框架:https://github.com/square/leakcanary
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.10'
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.12'
}
1 change: 0 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>

<!-- Android 11 软件包可见性适配 -->
Expand Down
6 changes: 1 addition & 5 deletions app/src/main/java/com/hjq/easy/demo/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@
import android.os.Environment;
import android.view.View;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hjq.easy.demo.http.api.SearchAuthorApi;
Expand All @@ -36,13 +34,11 @@
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
Expand Down Expand Up @@ -133,7 +129,7 @@ public void onHttpSuccess(HttpData<List<SearchAuthorApi.Bean>> result) {

} else if (viewId == R.id.btn_main_post) {

EasyHttp.post(MainActivity.this)
EasyHttp.post(this)
.api(new SearchBlogsApi()
.setKeyword("搬砖不再有"))
.request(new HttpCallbackProxy<HttpData<SearchBlogsApi.Bean>>(MainActivity.this) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,74 @@
*/
public final class HttpCacheManager {

private volatile static MMKV sMmkv;
private static final MMKV HTTP_CACHE_CONTENT = MMKV.mmkvWithID("http_cache_content");;

private static final MMKV HTTP_CACHE_TIME = MMKV.mmkvWithID("http_cache_time");

/**
* 生成缓存的 key
*/
public static String generateCacheKey(@NonNull HttpRequest<?> httpRequest) {
IRequestApi requestApi = httpRequest.getRequestApi();
return "请替换成当前的用户 id" + "\n" + requestApi.getApi() + "\n" + GsonFactory.getSingletonGson().toJson(requestApi);
}

/**
* 获取单例的 MMKV 实例
* 读取缓存
*/
public static MMKV getMmkv() {
if(sMmkv == null) {
synchronized (RequestHandler.class) {
if (sMmkv == null) {
sMmkv = MMKV.mmkvWithID("http_cache_id");
}
}
public static String readHttpCache(String cacheKey) {
String cacheValue = HTTP_CACHE_CONTENT.getString(cacheKey, null);
if ("".equals(cacheValue) || "{}".equals(cacheValue)) {
return null;
}
return sMmkv;
return cacheValue;
}

/**
* 生成缓存的 key
* 写入缓存
*/
public static String generateCacheKey(@NonNull HttpRequest<?> httpRequest) {
IRequestApi requestApi = httpRequest.getRequestApi();
return "用户 id" + "\n" + requestApi.getApi() + "\n" + GsonFactory.getSingletonGson().toJson(requestApi);
public static boolean writeHttpCache(String cacheKey, String cacheValue) {
return HTTP_CACHE_CONTENT.putString(cacheKey, cacheValue).commit();
}

/**
* 清理缓存
*/
public static void clearCache() {
HTTP_CACHE_CONTENT.clearMemoryCache();
HTTP_CACHE_CONTENT.clearAll();

HTTP_CACHE_TIME.clearMemoryCache();
HTTP_CACHE_TIME.clearAll();
}

/**
* 获取 Http 写入缓存的时间
*/
public static long getHttpCacheTime(String cacheKey) {
return HTTP_CACHE_TIME.getLong(cacheKey, 0);
}

/**
* 设置 Http 写入缓存的时间
*/
public static boolean setHttpCacheTime(String cacheKey, long cacheTime) {
return HTTP_CACHE_TIME.putLong(cacheKey, cacheTime).commit();
}

/**
* 判断缓存是否过期
*/
public static boolean isCacheInvalidate(String cacheKey, long maxCacheTime) {
if (maxCacheTime == Long.MAX_VALUE) {
// 表示缓存长期有效,永远不会过期
return false;
}
long httpCacheTime = getHttpCacheTime(cacheKey);
if (httpCacheTime == 0) {
// 表示不知道缓存的时间,这里默认当做已经过期了
return true;
}
return httpCacheTime + maxCacheTime < System.currentTimeMillis();
}
}
26 changes: 18 additions & 8 deletions app/src/main/java/com/hjq/easy/demo/http/model/RequestHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -200,14 +200,21 @@ public Exception downloadFail(@NonNull HttpRequest<?> httpRequest, @NonNull Exce
@Override
public Object readCache(@NonNull HttpRequest<?> httpRequest, @NonNull Type type, long cacheTime) {
String cacheKey = HttpCacheManager.generateCacheKey(httpRequest);
String cacheValue = HttpCacheManager.getMmkv().getString(cacheKey, null);
String cacheValue = HttpCacheManager.readHttpCache(cacheKey);
if (cacheValue == null || "".equals(cacheValue) || "{}".equals(cacheValue)) {
return null;
}
EasyLog.printLog(httpRequest, "----- readCache cacheKey -----");
EasyLog.printLog(httpRequest, "----- read cache key -----");
EasyLog.printJson(httpRequest, cacheKey);
EasyLog.printLog(httpRequest, "----- readCache cacheValue -----");
EasyLog.printLog(httpRequest, "----- read cache value -----");
EasyLog.printJson(httpRequest, cacheValue);
EasyLog.printLog(httpRequest, "cacheTime = " + cacheTime);
boolean cacheInvalidate = HttpCacheManager.isCacheInvalidate(cacheKey, cacheTime);
EasyLog.printLog(httpRequest, "cacheInvalidate = " + cacheInvalidate);
if (cacheInvalidate) {
// 表示缓存已经过期了,直接返回 null 给外层,表示缓存不可用
return null;
}
return GsonFactory.getSingletonGson().fromJson(cacheValue, type);
}

Expand All @@ -218,16 +225,19 @@ public boolean writeCache(@NonNull HttpRequest<?> httpRequest, @NonNull Response
if (cacheValue == null || "".equals(cacheValue) || "{}".equals(cacheValue)) {
return false;
}
EasyLog.printLog(httpRequest, "----- writeCache cacheKey -----");
EasyLog.printLog(httpRequest, "----- write cache key -----");
EasyLog.printJson(httpRequest, cacheKey);
EasyLog.printLog(httpRequest, "----- writeCache cacheValue -----");
EasyLog.printLog(httpRequest, "----- write cache value -----");
EasyLog.printJson(httpRequest, cacheValue);
return HttpCacheManager.getMmkv().putString(cacheKey, cacheValue).commit();
boolean writeHttpCacheResult = HttpCacheManager.writeHttpCache(cacheKey, cacheValue);
EasyLog.printLog(httpRequest, "writeHttpCacheResult = " + writeHttpCacheResult);
boolean refreshHttpCacheTimeResult = HttpCacheManager.setHttpCacheTime(cacheKey, System.currentTimeMillis());
EasyLog.printLog(httpRequest, "refreshHttpCacheTimeResult = " + refreshHttpCacheTimeResult);
return writeHttpCacheResult && refreshHttpCacheTimeResult;
}

@Override
public void clearCache() {
HttpCacheManager.getMmkv().clearMemoryCache();
HttpCacheManager.getMmkv().clearAll();
HttpCacheManager.clearCache();
}
}
4 changes: 2 additions & 2 deletions library/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ android {

defaultConfig {
minSdkVersion 16
versionCode 1200
versionName "12.0"
versionCode 1202
versionName "12.2"
}

// 使用 JDK 1.8
Expand Down
18 changes: 8 additions & 10 deletions library/src/main/java/com/hjq/http/EasyConfig.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
package com.hjq.http;

import com.hjq.http.config.DefaultHttpLogStrategy;
import com.hjq.http.config.IHttpLogStrategy;
import com.hjq.http.config.IRequestHandler;
import com.hjq.http.config.IRequestInterceptor;
import com.hjq.http.config.IRequestLogStrategy;
import com.hjq.http.config.IRequestServer;
import com.hjq.http.config.RequestServer;
import com.hjq.http.config.impl.EasyHttpLogStrategy;
import com.hjq.http.config.impl.EasyRequestServer;
import com.hjq.http.model.ThreadSchedulers;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import okhttp3.OkHttpClient;

/**
Expand Down Expand Up @@ -48,7 +46,7 @@ public static EasyConfig with(OkHttpClient client) {
/** 请求拦截器 */
private IRequestInterceptor mInterceptor;
/** 日志打印策略 */
private IHttpLogStrategy mLogStrategy;
private IRequestLogStrategy mLogStrategy;

/** OkHttp 客户端 */
private OkHttpClient mClient;
Expand Down Expand Up @@ -78,7 +76,7 @@ private EasyConfig(OkHttpClient client) {
}

public EasyConfig setServer(String host) {
return setServer(new RequestServer(host));
return setServer(new EasyRequestServer(host));
}

public EasyConfig setServer(IRequestServer server) {
Expand Down Expand Up @@ -157,7 +155,7 @@ public EasyConfig setThreadSchedulers(ThreadSchedulers schedulers) {
return this;
}

public EasyConfig setLogStrategy(IHttpLogStrategy strategy) {
public EasyConfig setLogStrategy(IRequestLogStrategy strategy) {
mLogStrategy = strategy;
return this;
}
Expand Down Expand Up @@ -218,7 +216,7 @@ public ThreadSchedulers getThreadSchedulers() {
return mThreadSchedulers;
}

public IHttpLogStrategy getLogStrategy() {
public IRequestLogStrategy getLogStrategy() {
return mLogStrategy;
}

Expand Down Expand Up @@ -260,7 +258,7 @@ public void into() {
}

if (mLogStrategy == null) {
mLogStrategy = new DefaultHttpLogStrategy();
mLogStrategy = new EasyHttpLogStrategy();
}
EasyConfig.setInstance(this);
}
Expand Down
Loading

0 comments on commit af97154

Please sign in to comment.