Request添加bodyStr、bodyBytes、bodyStream、toString方法

This commit is contained in:
Toint 2024-07-28 04:13:52 +08:00
parent 2384ea0425
commit 2ecb247861

View File

@ -12,7 +12,9 @@
package org.dromara.hutool.http.client;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.io.IoUtil;
import org.dromara.hutool.core.io.resource.Resource;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.map.MapUtil;
@ -278,6 +280,44 @@ public class Request implements HeaderOperation<Request> {
return this.body;
}
/**
* 获取请求体字符串
*
* @return 请求体字符串
*/
public String bodyStr() {
InputStream bodyStream = this.bodyStream();
if (bodyStream == null) {
return null;
}
return IoUtil.read(bodyStream, this.charset);
}
/**
* 获取请求体字节码
*
* @return 请求体字节码
*/
public byte[] bodyBytes() {
InputStream bodyStream = this.bodyStream();
if (bodyStream == null) {
return null;
}
return IoUtil.readBytes(bodyStream);
}
/**
* 获取请求体资源流
*
* @return 请求体资源流
*/
public InputStream bodyStream() {
if (this.body == null) {
return null;
}
return this.body.getStream();
}
/**
* 获取处理过的请求体即如果是非REST的GET请求始终返回{@code null}
*
@ -415,4 +455,25 @@ public class Request implements HeaderOperation<Request> {
return this.url();
}
@Override
public String toString() {
final StringBuilder sb = StrUtil.builder();
sb.append("Request Url: ").append(this.url).append(StrUtil.CRLF);
// header
sb.append("Request Headers: ").append(StrUtil.CRLF);
for (Map.Entry<String, ? extends Collection<String>> entry : this.headers.entrySet()) {
sb.append(" ")
.append(entry.getKey())
.append(": ")
.append(CollUtil.join(entry.getValue(), ","))
.append(StrUtil.CRLF);
}
// body
sb.append("Request Body: ").append(StrUtil.CRLF);
sb.append(" ").append(this.bodyStr()).append(StrUtil.CRLF);
return sb.toString();
}
}