MultipartBody 打印参数比较麻烦
kotlin:
if (requestBody is MultipartBody) {
val params = mutableMapOf<String, String>()
val files = mutableMapOf<String, String>()
requestBody.parts().forEach {
val body = it.body()
it.headers()?.let {
val header = it.value(0)
val split = header.replace(" ", "").replace("\"", "").split(";")
when (split.size) {
2 -> {
//文本参数
val keys = split[1].split("=")
if (keys.size > 1 && body.contentLength() < 1024) {
val key = keys[1]
val buffer = Buffer()
body.writeTo(buffer)
val value = buffer.readUtf8()
params[key] = value
}
}
3 -> {
//文件
val fileKeys = split[1].split("=")
val fileKey = if (fileKeys.size > 1) {
fileKeys[1]
} else ""
val nameValue = split[2].split("=")
val fileName = if (nameValue.size > 1) nameValue[1] else ""
files[fileKey] = fileName
}
}
}
}
println("文件-->$files")
println("文本-->$params")
}
java写法
if (requestBody instanceof MultipartBody) {
MultipartBody body = (MultipartBody) requestBody;
Map<String, String> params = new HashMap<>();
Map<String, String> files = new HashMap<>();
for (MultipartBody.Part part : body.parts()) {
RequestBody body1 = part.body();
Headers headers = part.headers();
if (headers != null && headers.size() > 0) {
String[] split = headers.value(0).replace(" ", "").replace("\"", "").split(";");
if (split.length == 2) {
//文本
String[] keys = split[1].split("=");
if (keys.length > 1 && body1.contentLength() < 1024) {
String key = keys[1];
String value = "";
Buffer buffer = new Buffer();
body.writeTo(buffer);
value = buffer.readUtf8();
params.put(key, value);
}
} else if (split.length == 3) {
//文件
String fileKey = "";
String fileName = "";
String[] keys = split[1].split("=");
String[] names = split[2].split("=");
if (keys.length > 1) fileKey = keys[1];
if (names.length > 1) fileName = names[1];
files.put(fileKey, fileName);
}
}
}
System.out.println("文本参数-->" + params);
System.out.println("文件参数-->" + files);
}