From ec8ed4c263fdccf8654314f323bc30be3a209698 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Android=20=E8=BD=AE=E5=AD=90=E5=93=A5?= Date: Thu, 5 Oct 2023 00:02:20 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8A=BD=E5=8F=96=E5=92=8C=E5=B0=81=E8=A3=85?= =?UTF-8?q?=20RequestBody=20=E8=AF=B7=E6=B1=82=E7=AD=96=E7=95=A5=20?= =?UTF-8?q?=E4=BC=98=E5=8C=96=20ThreadSchedulers=20=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/build.gradle | 10 +- library/build.gradle | 17 +- .../main/java/com/hjq/http/EasyConfig.java | 2 +- .../src/main/java/com/hjq/http/EasyUtils.java | 4 +- .../com/hjq/http/callback/BaseCallback.java | 2 +- .../hjq/http/config/IRequestBodyStrategy.java | 24 +++ .../com/hjq/http/config/IRequestServer.java | 6 +- .../com/hjq/http/config/IRequestType.java | 4 +- .../config/impl/RequestFormBodyStrategy.java | 185 ++++++++++++++++ .../config/impl/RequestJsonBodyStrategy.java | 28 +++ .../java/com/hjq/http/model/BodyType.java | 20 -- .../com/hjq/http/model/RequestBodyType.java | 24 +++ .../com/hjq/http/model/ThreadSchedulers.java | 4 +- .../com/hjq/http/request/BodyRequest.java | 197 +----------------- .../com/hjq/http/request/DownloadRequest.java | 18 +- .../com/hjq/http/request/HttpRequest.java | 26 +-- .../java/com/hjq/http/request/UrlRequest.java | 11 +- 17 files changed, 322 insertions(+), 260 deletions(-) create mode 100644 library/src/main/java/com/hjq/http/config/IRequestBodyStrategy.java create mode 100644 library/src/main/java/com/hjq/http/config/impl/RequestFormBodyStrategy.java create mode 100644 library/src/main/java/com/hjq/http/config/impl/RequestJsonBodyStrategy.java delete mode 100644 library/src/main/java/com/hjq/http/model/BodyType.java create mode 100644 library/src/main/java/com/hjq/http/model/RequestBodyType.java diff --git a/app/build.gradle b/app/build.gradle index 606189c..aedabfb 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -14,8 +14,8 @@ android { applicationId 'com.hjq.easy.demo' minSdkVersion 21 targetSdkVersion 31 - versionCode 1202 - versionName '12.2' + versionCode 1205 + versionName '12.5' } // 支持 JDK 1.8 @@ -48,9 +48,9 @@ android { } } - applicationVariants.all { variant -> + applicationVariants.configureEach { variant -> // apk 输出文件名配置 - variant.outputs.all { output -> + variant.outputs.configureEach { output -> outputFileName = rootProject.getName() + '.apk' } } @@ -73,7 +73,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:3.12.13' // 吐司框架:https://github.com/getActivity/Toaster - implementation 'com.github.getActivity:Toaster:12.3' + implementation 'com.github.getActivity:Toaster:12.5' // 权限请求框架:https://github.com/getActivity/XXPermissions implementation 'com.github.getActivity:XXPermissions:18.3' diff --git a/library/build.gradle b/library/build.gradle index 6d9c73c..c6193c8 100644 --- a/library/build.gradle +++ b/library/build.gradle @@ -5,8 +5,8 @@ android { defaultConfig { minSdkVersion 16 - versionCode 1202 - versionName "12.2" + versionCode 1205 + versionName "12.5" } // 使用 JDK 1.8 @@ -20,9 +20,9 @@ android { exclude 'META-INF/*******' } - android.libraryVariants.all { variant -> + android.libraryVariants.configureEach { variant -> // aar 输出文件名配置 - variant.outputs.all { output -> + variant.outputs.configureEach { output -> outputFileName = "${rootProject.name}-${android.defaultConfig.versionName}.aar" } } @@ -45,23 +45,24 @@ dependencies { implementation 'androidx.lifecycle:lifecycle-runtime:2.1.0' } -tasks.withType(Javadoc) { +tasks.withType(Javadoc).configureEach { options.addStringOption('Xdoclint:none', '-quiet') options.addStringOption('encoding', 'UTF-8') options.addStringOption('charSet', 'UTF-8') } -task sourcesJar(type: Jar) { +tasks.register('sourcesJar', Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' } -task javadoc(type: Javadoc) { +tasks.register('javadoc', Javadoc) { source = android.sourceSets.main.java.srcDirs classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) } -task javadocJar(type: Jar, dependsOn: javadoc) { +tasks.register('javadocJar', Jar) { + dependsOn javadoc classifier = 'javadoc' from javadoc.destinationDir } diff --git a/library/src/main/java/com/hjq/http/EasyConfig.java b/library/src/main/java/com/hjq/http/EasyConfig.java index d4a6887..0c2a70a 100644 --- a/library/src/main/java/com/hjq/http/EasyConfig.java +++ b/library/src/main/java/com/hjq/http/EasyConfig.java @@ -57,7 +57,7 @@ public static EasyConfig with(OkHttpClient client) { private HashMap mHeaders; /** 线程调度器 */ - private ThreadSchedulers mThreadSchedulers = ThreadSchedulers.MainThread; + private ThreadSchedulers mThreadSchedulers = ThreadSchedulers.MAIN; /** 日志开关 */ private boolean mLogEnabled = true; diff --git a/library/src/main/java/com/hjq/http/EasyUtils.java b/library/src/main/java/com/hjq/http/EasyUtils.java index 7221764..85984ec 100644 --- a/library/src/main/java/com/hjq/http/EasyUtils.java +++ b/library/src/main/java/com/hjq/http/EasyUtils.java @@ -76,14 +76,14 @@ public static void runOnIOThread(Runnable runnable) { */ public static void runOnAssignThread(ThreadSchedulers schedulers, Runnable runnable) { switch (schedulers) { - case IOThread: + case IO: if (isMainThread()) { runOnIOThread(runnable); } else { runnable.run(); } break; - case MainThread: + case MAIN: default: if (isMainThread()) { runnable.run(); diff --git a/library/src/main/java/com/hjq/http/callback/BaseCallback.java b/library/src/main/java/com/hjq/http/callback/BaseCallback.java index 0b11f2b..a1a728d 100644 --- a/library/src/main/java/com/hjq/http/callback/BaseCallback.java +++ b/library/src/main/java/com/hjq/http/callback/BaseCallback.java @@ -37,7 +37,7 @@ public abstract class BaseCallback implements Callback { public BaseCallback(@NonNull HttpRequest request) { mHttpRequest = request; // Lifecycle addObserver 需要在主线程中执行,所以这里要做一下线程转换 - EasyUtils.runOnAssignThread(ThreadSchedulers.MainThread, + EasyUtils.runOnAssignThread(ThreadSchedulers.MAIN, () -> HttpLifecycleManager.register(mHttpRequest.getLifecycleOwner())); } diff --git a/library/src/main/java/com/hjq/http/config/IRequestBodyStrategy.java b/library/src/main/java/com/hjq/http/config/IRequestBodyStrategy.java new file mode 100644 index 0000000..d2fac02 --- /dev/null +++ b/library/src/main/java/com/hjq/http/config/IRequestBodyStrategy.java @@ -0,0 +1,24 @@ +package com.hjq.http.config; + +import com.hjq.http.model.HttpParams; +import com.hjq.http.request.HttpRequest; +import okhttp3.RequestBody; + +/** + * author : Android 轮子哥 + * github : https://github.com/getActivity/EasyHttp + * time : 2023/09/23 + * desc : 请求 Body 策略接口 + */ +public interface IRequestBodyStrategy { + + /** + * 添加参数 + */ + void addParams(HttpParams params, String key, Object value); + + /** + * 创建 RequestBody + */ + RequestBody createRequestBody(HttpRequest httpRequest, HttpParams params); +} \ No newline at end of file diff --git a/library/src/main/java/com/hjq/http/config/IRequestServer.java b/library/src/main/java/com/hjq/http/config/IRequestServer.java index f51f2ec..2f10bc9 100644 --- a/library/src/main/java/com/hjq/http/config/IRequestServer.java +++ b/library/src/main/java/com/hjq/http/config/IRequestServer.java @@ -2,7 +2,7 @@ import androidx.annotation.NonNull; -import com.hjq.http.model.BodyType; +import com.hjq.http.model.RequestBodyType; import com.hjq.http.model.CacheMode; /** @@ -17,9 +17,9 @@ public interface IRequestServer extends @NonNull @Override - default BodyType getBodyType() { + default IRequestBodyStrategy getBodyType() { // 默认以表单的方式提交 - return BodyType.FORM; + return RequestBodyType.FORM; } @NonNull diff --git a/library/src/main/java/com/hjq/http/config/IRequestType.java b/library/src/main/java/com/hjq/http/config/IRequestType.java index fbe04ab..cbfe015 100644 --- a/library/src/main/java/com/hjq/http/config/IRequestType.java +++ b/library/src/main/java/com/hjq/http/config/IRequestType.java @@ -2,8 +2,6 @@ import androidx.annotation.NonNull; -import com.hjq.http.model.BodyType; - /** * author : Android 轮子哥 * github : https://github.com/getActivity/EasyHttp @@ -16,5 +14,5 @@ public interface IRequestType { * 获取参数的提交类型 */ @NonNull - BodyType getBodyType(); + IRequestBodyStrategy getBodyType(); } \ No newline at end of file diff --git a/library/src/main/java/com/hjq/http/config/impl/RequestFormBodyStrategy.java b/library/src/main/java/com/hjq/http/config/impl/RequestFormBodyStrategy.java new file mode 100644 index 0000000..c8b71a0 --- /dev/null +++ b/library/src/main/java/com/hjq/http/config/impl/RequestFormBodyStrategy.java @@ -0,0 +1,185 @@ +package com.hjq.http.config.impl; + +import android.text.TextUtils; +import com.hjq.http.EasyLog; +import com.hjq.http.body.UpdateBody; +import com.hjq.http.config.IRequestBodyStrategy; +import com.hjq.http.model.FileContentResolver; +import com.hjq.http.model.HttpParams; +import com.hjq.http.request.HttpRequest; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; +import okhttp3.FormBody; +import okhttp3.MultipartBody; +import okhttp3.RequestBody; +import okio.Okio; + +/** + * author : Android 轮子哥 + * github : https://github.com/getActivity/EasyHttp + * time : 2023/09/23 + * desc : RequestBody 表单策略实现接口 + */ +public class RequestFormBodyStrategy implements IRequestBodyStrategy { + + @Override + public void addParams(HttpParams params, String key, Object value) { + // 表单提交 + params.put(key, value); + } + + @Override + public RequestBody createRequestBody(HttpRequest httpRequest, HttpParams params) { + if (!params.isEmpty() && params.isMultipart()) { + return createMultipartRequestBody(httpRequest, params); + } + return createFormRequestBody(params); + } + + public RequestBody createFormRequestBody(HttpParams params) { + FormBody.Builder bodyBuilder = new FormBody.Builder(); + if (params.isEmpty()) { + return bodyBuilder.build(); + } + + for (String key : params.getKeys()) { + Object value = params.get(key); + + if (!(value instanceof List)) { + bodyBuilder.add(key, String.valueOf(value)); + continue; + } + + List list = (List) value; + for (Object itemValue : list) { + if (itemValue == null) { + continue; + } + bodyBuilder.add(key, String.valueOf(itemValue)); + } + } + return bodyBuilder.build(); + } + + public RequestBody createMultipartRequestBody(HttpRequest httpRequest, HttpParams params) { + MultipartBody.Builder bodyBuilder = new MultipartBody.Builder(); + bodyBuilder.setType(MultipartBody.FORM); + for (String key : params.getKeys()) { + Object value = params.get(key); + + if (value instanceof Map) { + // 如果这是一个 Map 集合 + Map map = ((Map) value); + for (Object itemKey : map.keySet()) { + if (itemKey == null) { + continue; + } + Object itemValue = map.get(itemKey); + if (itemValue == null) { + continue; + } + addFormData(httpRequest, bodyBuilder, String.valueOf(itemKey), itemValue); + } + continue; + } + + if (value instanceof List) { + // 如果这是一个 List 集合 + List list = (List) value; + for (Object itemValue : list) { + if (itemValue == null) { + continue; + } + addFormData(httpRequest, bodyBuilder, key, itemValue); + } + continue; + } + + addFormData(httpRequest, bodyBuilder, key, value); + } + + try { + return bodyBuilder.build(); + } catch (IllegalStateException ignored) { + // 如果参数为空则会抛出异常:Multipart body must have at least one part. + return new FormBody.Builder().build(); + } + } + + /** + * 添加参数 + */ + private void addFormData(HttpRequest httpRequest, MultipartBody.Builder bodyBuilder, String key, Object object) { + if (object instanceof File) { + // 如果这是一个 File 对象 + File file = (File) object; + String fileName = null; + if (file instanceof FileContentResolver) { + fileName = ((FileContentResolver) file).getFileName(); + } + if (TextUtils.isEmpty(fileName)) { + fileName = file.getName(); + } + + try { + MultipartBody.Part part; + if (file instanceof FileContentResolver) { + FileContentResolver fileContentResolver = (FileContentResolver) file; + InputStream inputStream = fileContentResolver.openInputStream(); + part = MultipartBody.Part.createFormData(key, fileName, new UpdateBody( + Okio.source(inputStream), fileContentResolver.getContentType(), + fileName, inputStream.available())); + } else { + part = MultipartBody.Part.createFormData(key, fileName, new UpdateBody(file)); + } + bodyBuilder.addPart(part); + } catch (FileNotFoundException e) { + // 文件不存在,将被忽略上传 + EasyLog.printLog(httpRequest, "File does not exist, will be ignored upload: " + + key + " = " + file.getPath()); + } catch (IOException e) { + EasyLog.printThrowable(httpRequest, e); + // 文件流读取失败,将被忽略上传 + EasyLog.printLog(httpRequest, "File stream reading failed and will be ignored upload: " + + key + " = " + file.getPath()); + } + return; + } + + if (object instanceof InputStream) { + // 如果这是一个 InputStream 对象 + InputStream inputStream = (InputStream) object; + try { + bodyBuilder.addPart(MultipartBody.Part.createFormData(key, null, new UpdateBody(inputStream, key))); + } catch (IOException e) { + EasyLog.printThrowable(httpRequest, e); + } + return; + } + + if (object instanceof RequestBody) { + // 如果这是一个自定义的 RequestBody 对象 + RequestBody requestBody = (RequestBody) object; + if (requestBody instanceof UpdateBody) { + bodyBuilder.addPart(MultipartBody.Part.createFormData(key, + ((UpdateBody) requestBody).getKeyName(), requestBody)); + } else { + bodyBuilder.addPart(MultipartBody.Part.createFormData(key, null, requestBody)); + } + return; + } + + if (object instanceof MultipartBody.Part) { + // 如果这是一个自定义的 MultipartBody.Part 对象 + bodyBuilder.addPart((MultipartBody.Part) object); + return; + } + + // 如果这是一个普通参数 + bodyBuilder.addFormDataPart(key, String.valueOf(object)); + } +} \ No newline at end of file diff --git a/library/src/main/java/com/hjq/http/config/impl/RequestJsonBodyStrategy.java b/library/src/main/java/com/hjq/http/config/impl/RequestJsonBodyStrategy.java new file mode 100644 index 0000000..053d124 --- /dev/null +++ b/library/src/main/java/com/hjq/http/config/impl/RequestJsonBodyStrategy.java @@ -0,0 +1,28 @@ +package com.hjq.http.config.impl; + +import com.hjq.http.EasyUtils; +import com.hjq.http.body.JsonBody; +import com.hjq.http.config.IRequestBodyStrategy; +import com.hjq.http.model.HttpParams; +import com.hjq.http.request.HttpRequest; +import okhttp3.RequestBody; + +/** + * author : Android 轮子哥 + * github : https://github.com/getActivity/EasyHttp + * time : 2023/09/23 + * desc : RequestBody Json 策略实现接口 + */ +public class RequestJsonBodyStrategy implements IRequestBodyStrategy { + + @Override + public void addParams(HttpParams params, String key, Object value) { + // Json 提交 + params.put(key, EasyUtils.convertObject(value)); + } + + @Override + public RequestBody createRequestBody(HttpRequest httpRequest, HttpParams params) { + return new JsonBody(params.getParams()); + } +} \ No newline at end of file diff --git a/library/src/main/java/com/hjq/http/model/BodyType.java b/library/src/main/java/com/hjq/http/model/BodyType.java deleted file mode 100644 index 6aa3626..0000000 --- a/library/src/main/java/com/hjq/http/model/BodyType.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.hjq.http.model; - -/** - * author : Android 轮子哥 - * github : https://github.com/getActivity/EasyHttp - * time : 2019/12/18 - * desc : 参数提交方式 - */ -public enum BodyType { - - /** - * 表单提交 - */ - FORM, - - /** - * JSON 提交 - */ - JSON -} \ No newline at end of file diff --git a/library/src/main/java/com/hjq/http/model/RequestBodyType.java b/library/src/main/java/com/hjq/http/model/RequestBodyType.java new file mode 100644 index 0000000..f2b435b --- /dev/null +++ b/library/src/main/java/com/hjq/http/model/RequestBodyType.java @@ -0,0 +1,24 @@ +package com.hjq.http.model; + +import com.hjq.http.config.impl.RequestFormBodyStrategy; +import com.hjq.http.config.impl.RequestJsonBodyStrategy; +import com.hjq.http.config.IRequestBodyStrategy; + +/** + * author : Android 轮子哥 + * github : https://github.com/getActivity/EasyHttp + * time : 2019/12/18 + * desc : 参数提交方式 + */ +public class RequestBodyType { + + /** + * 表单提交 + */ + public static final IRequestBodyStrategy FORM = new RequestFormBodyStrategy(); + + /** + * JSON 提交 + */ + public static final IRequestBodyStrategy JSON = new RequestJsonBodyStrategy(); +} \ No newline at end of file diff --git a/library/src/main/java/com/hjq/http/model/ThreadSchedulers.java b/library/src/main/java/com/hjq/http/model/ThreadSchedulers.java index 3792bcc..13cd8ed 100644 --- a/library/src/main/java/com/hjq/http/model/ThreadSchedulers.java +++ b/library/src/main/java/com/hjq/http/model/ThreadSchedulers.java @@ -9,8 +9,8 @@ public enum ThreadSchedulers { /** 主线程 */ - MainThread, + MAIN, /** IO 线程 */ - IOThread + IO } \ No newline at end of file diff --git a/library/src/main/java/com/hjq/http/request/BodyRequest.java b/library/src/main/java/com/hjq/http/request/BodyRequest.java index 9eaa757..4be00d4 100644 --- a/library/src/main/java/com/hjq/http/request/BodyRequest.java +++ b/library/src/main/java/com/hjq/http/request/BodyRequest.java @@ -1,10 +1,7 @@ package com.hjq.http.request; -import android.text.TextUtils; - import androidx.annotation.Nullable; import androidx.lifecycle.LifecycleOwner; - import com.hjq.http.EasyConfig; import com.hjq.http.EasyLog; import com.hjq.http.EasyUtils; @@ -12,27 +9,18 @@ import com.hjq.http.body.JsonBody; import com.hjq.http.body.ProgressBody; import com.hjq.http.body.TextBody; -import com.hjq.http.body.UpdateBody; +import com.hjq.http.config.IRequestBodyStrategy; import com.hjq.http.listener.OnHttpListener; import com.hjq.http.listener.OnUpdateListener; -import com.hjq.http.model.BodyType; -import com.hjq.http.model.FileContentResolver; import com.hjq.http.model.HttpHeaders; import com.hjq.http.model.HttpParams; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; import java.util.List; import java.util.Map; - import okhttp3.FormBody; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; -import okio.Okio; /** * author : Android 轮子哥 @@ -108,28 +96,18 @@ public void request(@Nullable OnHttpListener listener) { } @Override - protected void addHttpParams(HttpParams params, String key, Object value, BodyType bodyType) { - switch (bodyType) { - case JSON: - // Json 提交 - params.put(key, EasyUtils.convertObject(value)); - break; - case FORM: - default: - // 表单提交 - params.put(key, value); - break; - } + protected void addHttpParams(HttpParams params, String key, Object value, IRequestBodyStrategy requestBodyStrategy) { + requestBodyStrategy.addParams(params, key, value); } @Override - protected void addRequestParams(Request.Builder requestBuilder, HttpParams params, @Nullable String contentType, BodyType type) { - RequestBody body = mRequestBody != null ? mRequestBody : createRequestBody(params, contentType, type); + protected void addRequestParams(Request.Builder requestBuilder, HttpParams params, @Nullable String contentType, IRequestBodyStrategy requestBodyStrategy) { + RequestBody body = mRequestBody != null ? mRequestBody : createRequestBody(params, contentType, requestBodyStrategy); requestBuilder.method(getRequestMethod(), body); } @Override - protected void printRequestLog(Request request, HttpParams params, HttpHeaders headers, BodyType type) { + protected void printRequestLog(Request request, HttpParams params, HttpHeaders headers, IRequestBodyStrategy requestBodyStrategy) { if (!EasyConfig.getInstance().isLogEnabled()) { return; } @@ -186,7 +164,7 @@ protected void printRequestLog(Request request, HttpParams params, HttpHeaders h } } else if (body instanceof JsonBody) { // 打印 Json - EasyLog.printJson(this, String.valueOf(body)); + EasyLog.printJson(this, String.valueOf(params)); } else if (body instanceof TextBody) { // 打印文本 EasyLog.printLog(this, String.valueOf(body)); @@ -202,16 +180,8 @@ protected void printRequestLog(Request request, HttpParams params, HttpHeaders h /** * 组装 RequestBody 对象 */ - private RequestBody createRequestBody(HttpParams params, @Nullable String contentType, BodyType type) { - RequestBody requestBody; - - if (params.isMultipart() && !params.isEmpty()) { - requestBody = createMultipartBody(params); - } else if (type == BodyType.JSON) { - requestBody = createJsonBody(params); - } else { - requestBody = createFormBody(params); - } + private RequestBody createRequestBody(HttpParams params, @Nullable String contentType, IRequestBodyStrategy requestBodyStrategy) { + RequestBody requestBody = requestBodyStrategy.createRequestBody(this, params); // 如果外层需要自定义 Content-Type 这个字段,那么就使用装饰设计模式,对原有的 RequestBody 对象进行扩展 if (contentType != null && !"".equals(contentType)) { @@ -223,158 +193,11 @@ private RequestBody createRequestBody(HttpParams params, @Nullable String conten } } - // 如果当前设置了上传监听,那么久使用装饰设计模式,对原有的 RequestBody 对象进行扩展 + // 如果当前设置了上传监听,那么就使用装饰设计模式,对原有的 RequestBody 对象进行扩展 if (mUpdateListener != null) { requestBody = new ProgressBody(this, requestBody, getLifecycleOwner(), mUpdateListener); } return requestBody; } - - private RequestBody createMultipartBody(HttpParams params) { - MultipartBody.Builder bodyBuilder = new MultipartBody.Builder(); - bodyBuilder.setType(MultipartBody.FORM); - for (String key : params.getKeys()) { - Object value = params.get(key); - - if (value instanceof Map) { - // 如果这是一个 Map 集合 - Map map = ((Map) value); - for (Object itemKey : map.keySet()) { - if (itemKey == null) { - continue; - } - Object itemValue = map.get(itemKey); - if (itemValue == null) { - continue; - } - addFormData(bodyBuilder, String.valueOf(itemKey), itemValue); - } - continue; - } - - if (value instanceof List) { - // 如果这是一个 List 集合 - List list = (List) value; - for (Object itemValue : list) { - if (itemValue == null) { - continue; - } - addFormData(bodyBuilder, key, itemValue); - } - continue; - } - - addFormData(bodyBuilder, key, value); - } - - try { - return bodyBuilder.build(); - } catch (IllegalStateException ignored) { - // 如果参数为空则会抛出异常:Multipart body must have at least one part. - return new FormBody.Builder().build(); - } - } - - private RequestBody createJsonBody(HttpParams params) { - return new JsonBody(params.getParams()); - } - - private RequestBody createFormBody(HttpParams params) { - FormBody.Builder bodyBuilder = new FormBody.Builder(); - if (params.isEmpty()) { - return bodyBuilder.build(); - } - - for (String key : params.getKeys()) { - Object value = params.get(key); - - if (!(value instanceof List)) { - bodyBuilder.add(key, String.valueOf(value)); - continue; - } - - List list = (List) value; - for (Object itemValue : list) { - if (itemValue == null) { - continue; - } - bodyBuilder.add(key, String.valueOf(itemValue)); - } - } - return bodyBuilder.build(); - } - - /** - * 添加参数 - */ - private void addFormData(MultipartBody.Builder bodyBuilder, String key, Object object) { - if (object instanceof File) { - // 如果这是一个 File 对象 - File file = (File) object; - String fileName = null; - if (file instanceof FileContentResolver) { - fileName = ((FileContentResolver) file).getFileName(); - } - if (TextUtils.isEmpty(fileName)) { - fileName = file.getName(); - } - - try { - MultipartBody.Part part; - if (file instanceof FileContentResolver) { - FileContentResolver fileContentResolver = (FileContentResolver) file; - InputStream inputStream = fileContentResolver.openInputStream(); - part = MultipartBody.Part.createFormData(key, fileName, new UpdateBody( - Okio.source(inputStream), fileContentResolver.getContentType(), - fileName, inputStream.available())); - } else { - part = MultipartBody.Part.createFormData(key, fileName, new UpdateBody(file)); - } - bodyBuilder.addPart(part); - } catch (FileNotFoundException e) { - // 文件不存在,将被忽略上传 - EasyLog.printLog(this, "File does not exist, will be ignored upload: " + - key + " = " + file.getPath()); - } catch (IOException e) { - EasyLog.printThrowable(this, e); - // 文件流读取失败,将被忽略上传 - EasyLog.printLog(this, "File stream reading failed and will be ignored upload: " + - key + " = " + file.getPath()); - } - return; - } - - if (object instanceof InputStream) { - // 如果这是一个 InputStream 对象 - InputStream inputStream = (InputStream) object; - try { - bodyBuilder.addPart(MultipartBody.Part.createFormData(key, null, new UpdateBody(inputStream, key))); - } catch (IOException e) { - EasyLog.printThrowable(this, e); - } - return; - } - - if (object instanceof RequestBody) { - // 如果这是一个自定义的 RequestBody 对象 - RequestBody requestBody = (RequestBody) object; - if (requestBody instanceof UpdateBody) { - bodyBuilder.addPart(MultipartBody.Part.createFormData(key, - ((UpdateBody) requestBody).getKeyName(), requestBody)); - } else { - bodyBuilder.addPart(MultipartBody.Part.createFormData(key, null, requestBody)); - } - return; - } - - if (object instanceof MultipartBody.Part) { - // 如果这是一个自定义的 MultipartBody.Part 对象 - bodyBuilder.addPart((MultipartBody.Part) object); - return; - } - - // 如果这是一个普通参数 - bodyBuilder.addFormDataPart(key, String.valueOf(object)); - } } \ No newline at end of file diff --git a/library/src/main/java/com/hjq/http/request/DownloadRequest.java b/library/src/main/java/com/hjq/http/request/DownloadRequest.java index b289cb8..8715d1a 100644 --- a/library/src/main/java/com/hjq/http/request/DownloadRequest.java +++ b/library/src/main/java/com/hjq/http/request/DownloadRequest.java @@ -8,12 +8,12 @@ import com.hjq.http.EasyLog; import com.hjq.http.EasyUtils; import com.hjq.http.callback.DownloadCallback; +import com.hjq.http.config.IRequestBodyStrategy; import com.hjq.http.config.impl.EasyDownloadApi; import com.hjq.http.config.impl.EasyRequestServer; import com.hjq.http.lifecycle.HttpLifecycleManager; import com.hjq.http.listener.OnDownloadListener; import com.hjq.http.listener.OnHttpListener; -import com.hjq.http.model.BodyType; import com.hjq.http.model.CallProxy; import com.hjq.http.model.FileContentResolver; import com.hjq.http.model.HttpHeaders; @@ -186,23 +186,23 @@ public String getRequestMethod() { } @Override - protected Request createRequest(String url, String tag, HttpParams params, HttpHeaders headers, BodyType bodyType) { + protected Request createRequest(String url, String tag, HttpParams params, HttpHeaders headers, IRequestBodyStrategy requestBodyStrategy) { // 这里设置 api 的目的是为了打日志的时候不崩溃,因为现在打日志需要 api 对象 - return mRealRequest.api(getRequestApi()).createRequest(url, tag, params, headers, bodyType); + return mRealRequest.api(getRequestApi()).createRequest(url, tag, params, headers, requestBodyStrategy); } @Override - protected void addHttpParams(HttpParams params, String key, Object value, BodyType type) { - mRealRequest.addHttpParams(params, key, value, type); + protected void addHttpParams(HttpParams params, String key, Object value, IRequestBodyStrategy requestBodyStrategy) { + mRealRequest.addHttpParams(params, key, value, requestBodyStrategy); } @Override - protected void addRequestParams(Request.Builder requestBuilder, HttpParams params, @Nullable String contentType, BodyType type) { - mRealRequest.addRequestParams(requestBuilder, params, contentType, type); + protected void addRequestParams(Request.Builder requestBuilder, HttpParams params, @Nullable String contentType, IRequestBodyStrategy requestBodyStrategy) { + mRealRequest.addRequestParams(requestBuilder, params, contentType, requestBodyStrategy); } @Override - protected void printRequestLog(Request request, HttpParams params, HttpHeaders headers, BodyType type) { - mRealRequest.printRequestLog(request, params, headers, type); + protected void printRequestLog(Request request, HttpParams params, HttpHeaders headers, IRequestBodyStrategy requestBodyStrategy) { + mRealRequest.printRequestLog(request, params, headers, requestBodyStrategy); } } \ No newline at end of file diff --git a/library/src/main/java/com/hjq/http/request/HttpRequest.java b/library/src/main/java/com/hjq/http/request/HttpRequest.java index 0a435e3..98b6ff5 100644 --- a/library/src/main/java/com/hjq/http/request/HttpRequest.java +++ b/library/src/main/java/com/hjq/http/request/HttpRequest.java @@ -11,8 +11,10 @@ import com.hjq.http.annotation.HttpHeader; import com.hjq.http.annotation.HttpIgnore; import com.hjq.http.annotation.HttpRename; +import com.hjq.http.config.impl.RequestFormBodyStrategy; import com.hjq.http.callback.NormalCallback; import com.hjq.http.config.IRequestApi; +import com.hjq.http.config.IRequestBodyStrategy; import com.hjq.http.config.IRequestCache; import com.hjq.http.config.IRequestClient; import com.hjq.http.config.IRequestHandler; @@ -24,7 +26,7 @@ import com.hjq.http.config.impl.EasyRequestServer; import com.hjq.http.lifecycle.HttpLifecycleManager; import com.hjq.http.listener.OnHttpListener; -import com.hjq.http.model.BodyType; +import com.hjq.http.model.RequestBodyType; import com.hjq.http.model.CacheMode; import com.hjq.http.model.CallProxy; import com.hjq.http.model.ContentType; @@ -209,7 +211,7 @@ public T schedulers(@NonNull ThreadSchedulers schedulers) { @NonNull protected Call createCall() { - BodyType type = mRequestType.getBodyType(); + IRequestBodyStrategy requestBodyStrategy = mRequestType.getBodyType(); HttpParams params = new HttpParams(); HttpHeaders headers = new HttpHeaders(); @@ -221,9 +223,9 @@ protected Call createCall() { params.setMultipart(EasyUtils.isMultipartParameter(fields)); // 如果参数中包含流参数并且当前请求方式不是表单的话 - if (params.isMultipart() && type != BodyType.FORM) { + if (!params.isEmpty() && params.isMultipart() && !(requestBodyStrategy instanceof RequestFormBodyStrategy)) { // 就强制设置成以表单形式提交参数 - type = BodyType.FORM; + requestBodyStrategy = RequestBodyType.FORM; } for (Field field : fields) { @@ -276,7 +278,7 @@ protected Call createCall() { continue; } - addHttpParams(params, key, value, type); + addHttpParams(params, key, value, requestBodyStrategy); } catch (IllegalAccessException e) { EasyLog.printThrowable(this, e); @@ -288,7 +290,7 @@ protected Call createCall() { mRequestInterceptor.interceptArguments(this, params, headers); } - Request request = createRequest(url, mTag, params, headers, type); + Request request = createRequest(url, mTag, params, headers, requestBodyStrategy); if (mRequestInterceptor != null) { request = mRequestInterceptor.interceptRequest(this, request); @@ -563,20 +565,20 @@ protected void addHttpHeaders(HttpHeaders headers, String key, Object value) { /** * 添加请求参数 */ - protected abstract void addHttpParams(HttpParams params, String key, Object value, BodyType type); + protected abstract void addHttpParams(HttpParams params, String key, Object value, IRequestBodyStrategy requestBodyStrategy); /** * 创建请求的对象 */ - protected Request createRequest(String url, String tag, HttpParams params, HttpHeaders headers, BodyType bodyType) { + protected Request createRequest(String url, String tag, HttpParams params, HttpHeaders headers, IRequestBodyStrategy requestBodyStrategy) { Request.Builder requestBuilder = createRequestBuilder(url, tag); addRequestHeader(requestBuilder, headers); String contentType = headers.get(ContentType.HTTP_HEAD_KEY); - addRequestParams(requestBuilder, params, contentType, bodyType); + addRequestParams(requestBuilder, params, contentType, requestBodyStrategy); Request request = requestBuilder.build(); - printRequestLog(request, params, headers, bodyType); + printRequestLog(request, params, headers, requestBodyStrategy); return request; } @@ -621,12 +623,12 @@ protected void addRequestHeader(Request.Builder requestBuilder, HttpHeaders head /** * 添加请求参数 */ - protected abstract void addRequestParams(Request.Builder requestBuilder, HttpParams params, @Nullable String contentType, BodyType type); + protected abstract void addRequestParams(Request.Builder requestBuilder, HttpParams params, @Nullable String contentType, IRequestBodyStrategy requestBodyStrategy); /** * 打印请求日志 */ - protected abstract void printRequestLog(Request request, HttpParams params, HttpHeaders headers, BodyType type); + protected abstract void printRequestLog(Request request, HttpParams params, HttpHeaders headers, IRequestBodyStrategy requestBodyStrategy); /** * 生成日志的 TAG diff --git a/library/src/main/java/com/hjq/http/request/UrlRequest.java b/library/src/main/java/com/hjq/http/request/UrlRequest.java index a5872e4..70e2d67 100644 --- a/library/src/main/java/com/hjq/http/request/UrlRequest.java +++ b/library/src/main/java/com/hjq/http/request/UrlRequest.java @@ -2,17 +2,14 @@ import androidx.annotation.Nullable; import androidx.lifecycle.LifecycleOwner; - import com.hjq.http.EasyConfig; import com.hjq.http.EasyLog; -import com.hjq.http.model.BodyType; +import com.hjq.http.config.IRequestBodyStrategy; import com.hjq.http.model.HttpHeaders; import com.hjq.http.model.HttpParams; - import java.util.HashMap; import java.util.List; import java.util.Map; - import okhttp3.HttpUrl; import okhttp3.Request; @@ -29,12 +26,12 @@ public UrlRequest(LifecycleOwner lifecycleOwner) { } @Override - protected void addHttpParams(HttpParams params, String key, Object value, BodyType type) { + protected void addHttpParams(HttpParams params, String key, Object value, IRequestBodyStrategy requestBodyStrategy) { params.put(key, value); } @Override - protected void addRequestParams(Request.Builder requestBuilder, HttpParams params, @Nullable String contentType, BodyType type) { + protected void addRequestParams(Request.Builder requestBuilder, HttpParams params, @Nullable String contentType, IRequestBodyStrategy requestBodyStrategy) { HttpUrl.Builder urlBuilder = requestBuilder.build().url().newBuilder(); // 添加参数 if (!params.isEmpty()) { @@ -74,7 +71,7 @@ protected void addRequestParams(Request.Builder requestBuilder, HttpParams param } @Override - protected void printRequestLog(Request request, HttpParams params, HttpHeaders headers, BodyType type) { + protected void printRequestLog(Request request, HttpParams params, HttpHeaders headers, IRequestBodyStrategy requestBodyStrategy) { if (!EasyConfig.getInstance().isLogEnabled()) { return; }