Skip to content

Commit ec8ed4c

Browse files
committed
抽取和封装 RequestBody 请求策略
优化 ThreadSchedulers 字段命名
1 parent af97154 commit ec8ed4c

17 files changed

+322
-260
lines changed

app/build.gradle

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ android {
1414
applicationId 'com.hjq.easy.demo'
1515
minSdkVersion 21
1616
targetSdkVersion 31
17-
versionCode 1202
18-
versionName '12.2'
17+
versionCode 1205
18+
versionName '12.5'
1919
}
2020

2121
// 支持 JDK 1.8
@@ -48,9 +48,9 @@ android {
4848
}
4949
}
5050

51-
applicationVariants.all { variant ->
51+
applicationVariants.configureEach { variant ->
5252
// apk 输出文件名配置
53-
variant.outputs.all { output ->
53+
variant.outputs.configureEach { output ->
5454
outputFileName = rootProject.getName() + '.apk'
5555
}
5656
}
@@ -73,7 +73,7 @@ dependencies {
7373
implementation 'com.squareup.okhttp3:okhttp:3.12.13'
7474

7575
// 吐司框架:https://github.com/getActivity/Toaster
76-
implementation 'com.github.getActivity:Toaster:12.3'
76+
implementation 'com.github.getActivity:Toaster:12.5'
7777

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

library/build.gradle

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ android {
55

66
defaultConfig {
77
minSdkVersion 16
8-
versionCode 1202
9-
versionName "12.2"
8+
versionCode 1205
9+
versionName "12.5"
1010
}
1111

1212
// 使用 JDK 1.8
@@ -20,9 +20,9 @@ android {
2020
exclude 'META-INF/*******'
2121
}
2222

23-
android.libraryVariants.all { variant ->
23+
android.libraryVariants.configureEach { variant ->
2424
// aar 输出文件名配置
25-
variant.outputs.all { output ->
25+
variant.outputs.configureEach { output ->
2626
outputFileName = "${rootProject.name}-${android.defaultConfig.versionName}.aar"
2727
}
2828
}
@@ -45,23 +45,24 @@ dependencies {
4545
implementation 'androidx.lifecycle:lifecycle-runtime:2.1.0'
4646
}
4747

48-
tasks.withType(Javadoc) {
48+
tasks.withType(Javadoc).configureEach {
4949
options.addStringOption('Xdoclint:none', '-quiet')
5050
options.addStringOption('encoding', 'UTF-8')
5151
options.addStringOption('charSet', 'UTF-8')
5252
}
5353

54-
task sourcesJar(type: Jar) {
54+
tasks.register('sourcesJar', Jar) {
5555
from android.sourceSets.main.java.srcDirs
5656
classifier = 'sources'
5757
}
5858

59-
task javadoc(type: Javadoc) {
59+
tasks.register('javadoc', Javadoc) {
6060
source = android.sourceSets.main.java.srcDirs
6161
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
6262
}
6363

64-
task javadocJar(type: Jar, dependsOn: javadoc) {
64+
tasks.register('javadocJar', Jar) {
65+
dependsOn javadoc
6566
classifier = 'javadoc'
6667
from javadoc.destinationDir
6768
}

library/src/main/java/com/hjq/http/EasyConfig.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ public static EasyConfig with(OkHttpClient client) {
5757
private HashMap<String, String> mHeaders;
5858

5959
/** 线程调度器 */
60-
private ThreadSchedulers mThreadSchedulers = ThreadSchedulers.MainThread;
60+
private ThreadSchedulers mThreadSchedulers = ThreadSchedulers.MAIN;
6161

6262
/** 日志开关 */
6363
private boolean mLogEnabled = true;

library/src/main/java/com/hjq/http/EasyUtils.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,14 +76,14 @@ public static void runOnIOThread(Runnable runnable) {
7676
*/
7777
public static void runOnAssignThread(ThreadSchedulers schedulers, Runnable runnable) {
7878
switch (schedulers) {
79-
case IOThread:
79+
case IO:
8080
if (isMainThread()) {
8181
runOnIOThread(runnable);
8282
} else {
8383
runnable.run();
8484
}
8585
break;
86-
case MainThread:
86+
case MAIN:
8787
default:
8888
if (isMainThread()) {
8989
runnable.run();

library/src/main/java/com/hjq/http/callback/BaseCallback.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public abstract class BaseCallback implements Callback {
3737
public BaseCallback(@NonNull HttpRequest<?> request) {
3838
mHttpRequest = request;
3939
// Lifecycle addObserver 需要在主线程中执行,所以这里要做一下线程转换
40-
EasyUtils.runOnAssignThread(ThreadSchedulers.MainThread,
40+
EasyUtils.runOnAssignThread(ThreadSchedulers.MAIN,
4141
() -> HttpLifecycleManager.register(mHttpRequest.getLifecycleOwner()));
4242
}
4343

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.hjq.http.config;
2+
3+
import com.hjq.http.model.HttpParams;
4+
import com.hjq.http.request.HttpRequest;
5+
import okhttp3.RequestBody;
6+
7+
/**
8+
* author : Android 轮子哥
9+
* github : https://github.com/getActivity/EasyHttp
10+
* time : 2023/09/23
11+
* desc : 请求 Body 策略接口
12+
*/
13+
public interface IRequestBodyStrategy {
14+
15+
/**
16+
* 添加参数
17+
*/
18+
void addParams(HttpParams params, String key, Object value);
19+
20+
/**
21+
* 创建 RequestBody
22+
*/
23+
RequestBody createRequestBody(HttpRequest<?> httpRequest, HttpParams params);
24+
}

library/src/main/java/com/hjq/http/config/IRequestServer.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import androidx.annotation.NonNull;
44

5-
import com.hjq.http.model.BodyType;
5+
import com.hjq.http.model.RequestBodyType;
66
import com.hjq.http.model.CacheMode;
77

88
/**
@@ -17,9 +17,9 @@ public interface IRequestServer extends
1717

1818
@NonNull
1919
@Override
20-
default BodyType getBodyType() {
20+
default IRequestBodyStrategy getBodyType() {
2121
// 默认以表单的方式提交
22-
return BodyType.FORM;
22+
return RequestBodyType.FORM;
2323
}
2424

2525
@NonNull

library/src/main/java/com/hjq/http/config/IRequestType.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22

33
import androidx.annotation.NonNull;
44

5-
import com.hjq.http.model.BodyType;
6-
75
/**
86
* author : Android 轮子哥
97
* github : https://github.com/getActivity/EasyHttp
@@ -16,5 +14,5 @@ public interface IRequestType {
1614
* 获取参数的提交类型
1715
*/
1816
@NonNull
19-
BodyType getBodyType();
17+
IRequestBodyStrategy getBodyType();
2018
}
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
package com.hjq.http.config.impl;
2+
3+
import android.text.TextUtils;
4+
import com.hjq.http.EasyLog;
5+
import com.hjq.http.body.UpdateBody;
6+
import com.hjq.http.config.IRequestBodyStrategy;
7+
import com.hjq.http.model.FileContentResolver;
8+
import com.hjq.http.model.HttpParams;
9+
import com.hjq.http.request.HttpRequest;
10+
import java.io.File;
11+
import java.io.FileNotFoundException;
12+
import java.io.IOException;
13+
import java.io.InputStream;
14+
import java.util.List;
15+
import java.util.Map;
16+
import okhttp3.FormBody;
17+
import okhttp3.MultipartBody;
18+
import okhttp3.RequestBody;
19+
import okio.Okio;
20+
21+
/**
22+
* author : Android 轮子哥
23+
* github : https://github.com/getActivity/EasyHttp
24+
* time : 2023/09/23
25+
* desc : RequestBody 表单策略实现接口
26+
*/
27+
public class RequestFormBodyStrategy implements IRequestBodyStrategy {
28+
29+
@Override
30+
public void addParams(HttpParams params, String key, Object value) {
31+
// 表单提交
32+
params.put(key, value);
33+
}
34+
35+
@Override
36+
public RequestBody createRequestBody(HttpRequest<?> httpRequest, HttpParams params) {
37+
if (!params.isEmpty() && params.isMultipart()) {
38+
return createMultipartRequestBody(httpRequest, params);
39+
}
40+
return createFormRequestBody(params);
41+
}
42+
43+
public RequestBody createFormRequestBody(HttpParams params) {
44+
FormBody.Builder bodyBuilder = new FormBody.Builder();
45+
if (params.isEmpty()) {
46+
return bodyBuilder.build();
47+
}
48+
49+
for (String key : params.getKeys()) {
50+
Object value = params.get(key);
51+
52+
if (!(value instanceof List)) {
53+
bodyBuilder.add(key, String.valueOf(value));
54+
continue;
55+
}
56+
57+
List<?> list = (List<?>) value;
58+
for (Object itemValue : list) {
59+
if (itemValue == null) {
60+
continue;
61+
}
62+
bodyBuilder.add(key, String.valueOf(itemValue));
63+
}
64+
}
65+
return bodyBuilder.build();
66+
}
67+
68+
public RequestBody createMultipartRequestBody(HttpRequest<?> httpRequest, HttpParams params) {
69+
MultipartBody.Builder bodyBuilder = new MultipartBody.Builder();
70+
bodyBuilder.setType(MultipartBody.FORM);
71+
for (String key : params.getKeys()) {
72+
Object value = params.get(key);
73+
74+
if (value instanceof Map) {
75+
// 如果这是一个 Map 集合
76+
Map<?, ?> map = ((Map<?, ?>) value);
77+
for (Object itemKey : map.keySet()) {
78+
if (itemKey == null) {
79+
continue;
80+
}
81+
Object itemValue = map.get(itemKey);
82+
if (itemValue == null) {
83+
continue;
84+
}
85+
addFormData(httpRequest, bodyBuilder, String.valueOf(itemKey), itemValue);
86+
}
87+
continue;
88+
}
89+
90+
if (value instanceof List) {
91+
// 如果这是一个 List 集合
92+
List<?> list = (List<?>) value;
93+
for (Object itemValue : list) {
94+
if (itemValue == null) {
95+
continue;
96+
}
97+
addFormData(httpRequest, bodyBuilder, key, itemValue);
98+
}
99+
continue;
100+
}
101+
102+
addFormData(httpRequest, bodyBuilder, key, value);
103+
}
104+
105+
try {
106+
return bodyBuilder.build();
107+
} catch (IllegalStateException ignored) {
108+
// 如果参数为空则会抛出异常:Multipart body must have at least one part.
109+
return new FormBody.Builder().build();
110+
}
111+
}
112+
113+
/**
114+
* 添加参数
115+
*/
116+
private void addFormData(HttpRequest<?> httpRequest, MultipartBody.Builder bodyBuilder, String key, Object object) {
117+
if (object instanceof File) {
118+
// 如果这是一个 File 对象
119+
File file = (File) object;
120+
String fileName = null;
121+
if (file instanceof FileContentResolver) {
122+
fileName = ((FileContentResolver) file).getFileName();
123+
}
124+
if (TextUtils.isEmpty(fileName)) {
125+
fileName = file.getName();
126+
}
127+
128+
try {
129+
MultipartBody.Part part;
130+
if (file instanceof FileContentResolver) {
131+
FileContentResolver fileContentResolver = (FileContentResolver) file;
132+
InputStream inputStream = fileContentResolver.openInputStream();
133+
part = MultipartBody.Part.createFormData(key, fileName, new UpdateBody(
134+
Okio.source(inputStream), fileContentResolver.getContentType(),
135+
fileName, inputStream.available()));
136+
} else {
137+
part = MultipartBody.Part.createFormData(key, fileName, new UpdateBody(file));
138+
}
139+
bodyBuilder.addPart(part);
140+
} catch (FileNotFoundException e) {
141+
// 文件不存在,将被忽略上传
142+
EasyLog.printLog(httpRequest, "File does not exist, will be ignored upload: " +
143+
key + " = " + file.getPath());
144+
} catch (IOException e) {
145+
EasyLog.printThrowable(httpRequest, e);
146+
// 文件流读取失败,将被忽略上传
147+
EasyLog.printLog(httpRequest, "File stream reading failed and will be ignored upload: " +
148+
key + " = " + file.getPath());
149+
}
150+
return;
151+
}
152+
153+
if (object instanceof InputStream) {
154+
// 如果这是一个 InputStream 对象
155+
InputStream inputStream = (InputStream) object;
156+
try {
157+
bodyBuilder.addPart(MultipartBody.Part.createFormData(key, null, new UpdateBody(inputStream, key)));
158+
} catch (IOException e) {
159+
EasyLog.printThrowable(httpRequest, e);
160+
}
161+
return;
162+
}
163+
164+
if (object instanceof RequestBody) {
165+
// 如果这是一个自定义的 RequestBody 对象
166+
RequestBody requestBody = (RequestBody) object;
167+
if (requestBody instanceof UpdateBody) {
168+
bodyBuilder.addPart(MultipartBody.Part.createFormData(key,
169+
((UpdateBody) requestBody).getKeyName(), requestBody));
170+
} else {
171+
bodyBuilder.addPart(MultipartBody.Part.createFormData(key, null, requestBody));
172+
}
173+
return;
174+
}
175+
176+
if (object instanceof MultipartBody.Part) {
177+
// 如果这是一个自定义的 MultipartBody.Part 对象
178+
bodyBuilder.addPart((MultipartBody.Part) object);
179+
return;
180+
}
181+
182+
// 如果这是一个普通参数
183+
bodyBuilder.addFormDataPart(key, String.valueOf(object));
184+
}
185+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.hjq.http.config.impl;
2+
3+
import com.hjq.http.EasyUtils;
4+
import com.hjq.http.body.JsonBody;
5+
import com.hjq.http.config.IRequestBodyStrategy;
6+
import com.hjq.http.model.HttpParams;
7+
import com.hjq.http.request.HttpRequest;
8+
import okhttp3.RequestBody;
9+
10+
/**
11+
* author : Android 轮子哥
12+
* github : https://github.com/getActivity/EasyHttp
13+
* time : 2023/09/23
14+
* desc : RequestBody Json 策略实现接口
15+
*/
16+
public class RequestJsonBodyStrategy implements IRequestBodyStrategy {
17+
18+
@Override
19+
public void addParams(HttpParams params, String key, Object value) {
20+
// Json 提交
21+
params.put(key, EasyUtils.convertObject(value));
22+
}
23+
24+
@Override
25+
public RequestBody createRequestBody(HttpRequest<?> httpRequest, HttpParams params) {
26+
return new JsonBody(params.getParams());
27+
}
28+
}

0 commit comments

Comments
 (0)