use of com.lzy.okgo.model.HttpParams in project okhttp-OkGo by jeasonlzy.
the class HttpUtils method generateMultipartRequestBody.
/**
* 生成类似表单的请求体
*/
public static RequestBody generateMultipartRequestBody(HttpParams params, boolean isMultipart) {
if (params.fileParamsMap.isEmpty() && !isMultipart) {
// 表单提交,没有文件
FormBody.Builder bodyBuilder = new FormBody.Builder();
for (String key : params.urlParamsMap.keySet()) {
List<String> urlValues = params.urlParamsMap.get(key);
for (String value : urlValues) {
bodyBuilder.addEncoded(key, value);
}
}
return bodyBuilder.build();
} else {
// 表单提交,有文件
MultipartBody.Builder multipartBodybuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
// 拼接键值对
if (!params.urlParamsMap.isEmpty()) {
for (Map.Entry<String, List<String>> entry : params.urlParamsMap.entrySet()) {
List<String> urlValues = entry.getValue();
for (String value : urlValues) {
multipartBodybuilder.addFormDataPart(entry.getKey(), value);
}
}
}
// 拼接文件
for (Map.Entry<String, List<HttpParams.FileWrapper>> entry : params.fileParamsMap.entrySet()) {
List<HttpParams.FileWrapper> fileValues = entry.getValue();
for (HttpParams.FileWrapper fileWrapper : fileValues) {
RequestBody fileBody = RequestBody.create(fileWrapper.contentType, fileWrapper.file);
multipartBodybuilder.addFormDataPart(entry.getKey(), fileWrapper.fileName, fileBody);
}
}
return multipartBodybuilder.build();
}
}
Aggregations