Skip to content

Commit

Permalink
优化日志打印逻辑
Browse files Browse the repository at this point in the history
优化 md5 校验逻辑
新增支持自定义日志 TAG
新增支持打印请求耗时
删除一些已经标记过时方法
纠正某个英文单词书写错误
修复参数解析逻辑上的 Bug
  • Loading branch information
getActivity committed Apr 5, 2020
1 parent 12fd135 commit df189b5
Show file tree
Hide file tree
Showing 23 changed files with 455 additions and 432 deletions.
Binary file modified EasyHttp.apk
Binary file not shown.
522 changes: 265 additions & 257 deletions README.md

Large diffs are not rendered by default.

100 changes: 51 additions & 49 deletions app/build.gradle
Original file line number Diff line number Diff line change
@@ -1,50 +1,52 @@
apply plugin: 'com.android.application'

android {
compileSdkVersion 28

// 支持 JDK 1.8
compileOptions {
targetCompatibility JavaVersion.VERSION_1_8
sourceCompatibility JavaVersion.VERSION_1_8
}

defaultConfig {
applicationId "com.hjq.http.demo"
minSdkVersion 14
targetSdkVersion 28
versionCode 50
versionName "5.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation project(':library')

implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'

// 标题栏:https://github.com/getActivity/TitleBar
implementation 'com.hjq:titlebar:6.0'
// 吐司工具类:https://github.com/getActivity/ToastUtils
implementation 'com.hjq:toast:8.0'
// 权限请求框架:https://github.com/getActivity/XXPermissions
implementation 'com.hjq:xxpermissions:6.0'

// Json 解析框架:https://github.com/google/gson
implementation 'com.google.code.gson:gson:2.8.5'
// OkHttp 网络框架:https://github.com/square/okhttp
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
apply plugin: 'com.android.application'

android {
compileSdkVersion 28

// 支持 JDK 1.8
compileOptions {
targetCompatibility JavaVersion.VERSION_1_8
sourceCompatibility JavaVersion.VERSION_1_8
}

defaultConfig {
applicationId "com.hjq.http.demo"
minSdkVersion 14
targetSdkVersion 28
versionCode 60
versionName "6.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation project(':library')

implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'

// 标题栏:https://github.com/getActivity/TitleBar
implementation 'com.hjq:titlebar:6.0'
// 吐司工具类:https://github.com/getActivity/ToastUtils
implementation 'com.hjq:toast:8.0'
// 权限请求框架:https://github.com/getActivity/XXPermissions
implementation 'com.hjq:xxpermissions:6.2'
// Json 解析框架:https://github.com/google/gson
implementation 'com.google.code.gson:gson:2.8.5'
// OkHttp 框架:https://github.com/square/okhttp
// 升级注意事项:https://www.jianshu.com/p/d12d0f536f55
implementation 'com.squareup.okhttp3:okhttp:3.12.10'
// 日志调试:https://github.com/getActivity/Logcat
debugImplementation 'com.hjq:logcat:6.0'
}
6 changes: 5 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@
android:resource="@xml/file_paths" />
</provider>

<activity android:name=".MainActivity">
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|keyboardHidden"
android:launchMode="singleTop"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
Expand Down
6 changes: 3 additions & 3 deletions app/src/main/java/com/hjq/http/demo/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public void onClick(View v) {
case R.id.btn_main_get:
EasyHttp.get(this)
.api(new SearchAuthorApi()
.setAuthor("鸿洋"))
.setAuthor("鸿洋"))
.request(new HttpCallback<HttpData<SearchBean>>(this) {

@Override
Expand All @@ -115,12 +115,12 @@ public void onSucceed(HttpData<SearchBean> result) {
case R.id.btn_main_post:
EasyHttp.post(this)
.api(new SearchBlogsApi()
.setKeyword("搬砖不再有"))
.setKeyword("搬砖不再有"))
.request(new HttpCallback<HttpData<SearchBean>>(this) {

@Override
public void onSucceed(HttpData<SearchBean> result) {
ToastUtils.show("请求成功" + result.getData().getSize());
ToastUtils.show("请求成功");
}
});
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,6 @@ public Exception requestFail(Context context, Exception e) {
e = new HttpException(e.getMessage(), e);
}
}

// 打印错误信息
EasyLog.print(e);
return e;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ public SearchBlogsApi setKeyword(String keyword) {
this.keyword = keyword;
return this;
}
}
}
23 changes: 11 additions & 12 deletions library/build.gradle
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// 文件开头配置
apply plugin: 'com.android.library'
apply plugin: 'com.novoda.bintray-release'

Expand All @@ -14,26 +13,26 @@ android {
defaultConfig {
minSdkVersion 14
targetSdkVersion 26
versionCode 50
versionName "5.0"
versionCode 60
versionName "6.0"
}
}

dependencies {
compileOnly 'com.squareup.okhttp3:okhttp:3.12.1'
compileOnly 'com.android.support:support-fragment:26.0.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.10'
implementation 'com.android.support:support-fragment:26.0.0'
}

publish {
userOrg = 'getactivity'//填写bintray用户名,注意大小写
groupId = 'com.hjq'//定义的maven group id最终引用形式
artifactId = 'http'//maven的artifact id
version = '5.0'//maven 上发布版本号
description = 'Easy-to-use network request framework'//描述,自己定义
website = "https://github.com/getActivity/EasyHttp"//项目在github中的地址
userOrg = 'getactivity'
groupId = 'com.hjq'
artifactId = 'http'
version = '6.0'
description = 'Easy-to-use network request framework'
website = "https://github.com/getActivity/EasyHttp"
}

tasks.withType(Javadoc) {//防止编码问题
tasks.withType(Javadoc) {
options.addStringOption('Xdoclint:none', '-quiet')
options.addStringOption('encoding', 'UTF-8')
options.addStringOption('charSet', 'UTF-8')
Expand Down
11 changes: 11 additions & 0 deletions library/src/main/java/com/hjq/http/EasyConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ public static EasyConfig with(OkHttpClient client) {

/** 日志开关 */
private boolean mLogEnabled = true;
/** 日志 TAG */
private String mLogTag = "EasyHttp";
/** 重试次数 */
private int mRetryCount;

Expand Down Expand Up @@ -104,6 +106,11 @@ public EasyConfig setLogEnabled(boolean enabled) {
return this;
}

public EasyConfig setLogTag(String tag) {
mLogTag = tag;
return this;
}

public EasyConfig setRetryCount(int count) {
if (count < 0) {
throw new IllegalArgumentException("The number of retries must be greater than 0");
Expand Down Expand Up @@ -136,6 +143,10 @@ public boolean isLogEnabled() {
return mLogEnabled;
}

public String getLogTag() {
return mLogTag;
}

public int getRetryCount() {
return mRetryCount;
}
Expand Down
9 changes: 4 additions & 5 deletions library/src/main/java/com/hjq/http/EasyLog.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.hjq.http;

import android.text.TextUtils;
import android.util.Log;

/**
Expand All @@ -10,8 +11,6 @@
*/
public final class EasyLog {

private static final String TAG = "EasyHttp";

/**
* 日志开关
*/
Expand All @@ -24,7 +23,7 @@ public static boolean isEnable() {
*/
public static void print(String log) {
if (isEnable()) {
Log.d(TAG, log != null ? log : "null");
Log.d(EasyConfig.getInstance().getLogTag(), log != null ? log : "null");
}
}

Expand All @@ -33,7 +32,7 @@ public static void print(String log) {
*/
public static void print(Throwable throwable) {
if (EasyConfig.getInstance().isLogEnabled()) {
throwable.printStackTrace();
Log.e(EasyConfig.getInstance().getLogTag(), throwable.getMessage(), throwable);
}
}

Expand All @@ -57,7 +56,7 @@ public static void print() {
public static void json(String json) {
if (isEnable()) {
String text = stringToJSON(json);
if (text != null && !"".equals(text)) {
if (!TextUtils.isEmpty(text)) {
// 打印 Json 数据最好换一行再打印会好看一点
text = " \n" + text;

Expand Down
22 changes: 16 additions & 6 deletions library/src/main/java/com/hjq/http/callback/DownloadCallback.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.hjq.http.callback;

import android.text.TextUtils;

import com.hjq.http.EasyLog;
import com.hjq.http.EasyUtils;
import com.hjq.http.exception.MD5Exception;
Expand All @@ -23,6 +25,9 @@
*/
public final class DownloadCallback extends BaseCallback {

/** 文件 MD5 正则表达式 */
private static final String FILE_MD5_REGEX = "^[\\w]{32}$";

/** 下载任务 */
private DownloadInfo mDownloadInfo;
/** 保存的文件 */
Expand All @@ -44,9 +49,14 @@ public DownloadCallback(CallProxy call, File file, String md5, OnDownloadListene

@Override
protected void onResponse(Response response) throws Exception {
if (mMD5 == null || "".equals(mMD5)) {
// 如果没有指定文件的 md5 值
if (mMD5 == null) {
// 获取响应头中的文件 MD5 值
mMD5 = response.header("Content-MD5");
String md5 = response.header("Content-MD5");
// 这个 md5 值必须是文件的 md5 值
if (!TextUtils.isEmpty(md5) && md5.matches(FILE_MD5_REGEX)) {
mMD5 = md5;
}
}

EasyUtils.createFolder(mFile.getParentFile());
Expand All @@ -62,7 +72,7 @@ protected void onResponse(Response response) throws Exception {

mDownloadInfo.setTotalLength(body.contentLength());
// 如果这个文件已经下载过,并且经过校验 MD5 是同一个文件的话,就直接回调下载成功监听
if (mMD5 != null && !"".equals(mMD5) && mFile.exists() && mFile.isFile() && mMD5.equalsIgnoreCase(EasyUtils.getFileMD5(mFile))) {
if (!TextUtils.isEmpty(mMD5) && mFile.exists() && mFile.isFile() && mMD5.equalsIgnoreCase(EasyUtils.getFileMD5(mFile))) {
EasyUtils.runOnUiThread(mListener != null, () -> {
mDownloadInfo.setDownloadLength(mDownloadInfo.getTotalLength());
mListener.onComplete(mDownloadInfo);
Expand All @@ -89,9 +99,9 @@ protected void onResponse(Response response) throws Exception {
outputStream.flush();

EasyUtils.runOnUiThread(mListener != null, () -> {
String fileMD5 = EasyUtils.getFileMD5(mDownloadInfo.getFile());
if (mMD5 != null && !"".equals(mMD5) && !mMD5.equalsIgnoreCase(fileMD5)) {
onFailure(new MD5Exception("MD5 verify failure", fileMD5));
String md5 = EasyUtils.getFileMD5(mDownloadInfo.getFile());
if (!TextUtils.isEmpty(mMD5) && !mMD5.equalsIgnoreCase(md5)) {
onFailure(new MD5Exception("MD5 verify failure", md5));
} else {
mListener.onComplete(mDownloadInfo);
mListener.onEnd(getCall());
Expand Down
10 changes: 4 additions & 6 deletions library/src/main/java/com/hjq/http/callback/NormalCallback.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,15 @@ public final class NormalCallback extends BaseCallback {

private Context mContext;
private OnHttpListener mListener;
private long mRequestTime;

public NormalCallback(Context context, CallProxy call, OnHttpListener listener) {
super(call);
mContext = context;
mListener = listener;
mRequestTime = System.currentTimeMillis();

EasyUtils.runOnUiThread(mListener != null, () -> {
mListener.onStart(call);
EasyConfig.getInstance().getHandler().requestStart(context, call);
});
EasyUtils.runOnUiThread(mListener != null, () -> mListener.onStart(call));
}

@SuppressWarnings("unchecked")
Expand All @@ -48,11 +47,11 @@ protected void onResponse(Response response) throws Exception {
type = ((ParameterizedType) mListener.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}

EasyLog.print("RequestTime:" + (System.currentTimeMillis() - mRequestTime) + " ms");
final Object result = EasyConfig.getInstance().getHandler().requestSucceed(mContext, response, type);
EasyUtils.runOnUiThread(mListener != null, () -> {
mListener.onSucceed(result);
mListener.onEnd(getCall());
EasyConfig.getInstance().getHandler().requestEnd(mContext, getCall());
});
}

Expand All @@ -63,7 +62,6 @@ protected void onFailure(Exception e) {
EasyUtils.runOnUiThread(mListener != null, () -> {
mListener.onFail(exception);
mListener.onEnd(getCall());
EasyConfig.getInstance().getHandler().requestEnd(mContext, getCall());
});
}
}
Loading

0 comments on commit df189b5

Please sign in to comment.