Spring Boot 将 InputStream 输入流转换为 String
Spring Boot 大约 1214 字StreamUtils
Spring
中提供了StreamUtils
工具类,将InputStream
转换为String
。
注意:不会关闭流。
使用
假设转换HttpServletRequest
的输入流为String
。
HttpServletRequest request = xxx;
String content = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
源码
// org.springframework.util.StreamUtils
public abstract class StreamUtils {
/**
* Copy the contents of the given InputStream into a String.
* <p>Leaves the stream open when done.
* @param in the InputStream to copy from (may be {@code null} or empty)
* @param charset the {@link Charset} to use to decode the bytes
* @return the String that has been copied to (possibly empty)
* @throws IOException in case of I/O errors
*/
public static String copyToString(@Nullable InputStream in, Charset charset) throws IOException {
if (in == null) {
return "";
}
StringBuilder out = new StringBuilder();
InputStreamReader reader = new InputStreamReader(in, charset);
char[] buffer = new char[BUFFER_SIZE];
int charsRead;
while ((charsRead = reader.read(buffer)) != -1) {
out.append(buffer, 0, charsRead);
}
return out.toString();
}
}
阅读 52 · 发布于 2023-01-24
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
IDEA 调试 Java 多线程代码阅读 1106
-
Spring Boot 设置 Cookie 和 Session 过期时间阅读 6778
-
Golang 字符串与字节数组互相转换阅读 3614
-
minikube 安装 Kubernetes ingress 插件报错 timed out waiting for the condition阅读 412
-
Spring Boot 中的 ApplicationRunner 和 CommandLineRunner阅读 2700
-
JavaScript onbeforeunload 监听页面关闭事件阅读 1619
-
npm Windows 平台 install 报错阅读 6137
-
MySQL 中的覆盖索引阅读 1421
-
Android 软键盘遮挡控件阅读 1546
-
设计模式之策略模式阅读 2556