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();
}
}
阅读 1029 · 发布于 2023-01-24
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
IDEA 使用 Kubernetes 瑞士军刀 Telepresence 进行网络代理阅读 855
-
算法:二叉树的层序遍历阅读 1163
-
前缀表达式、中缀表达式、后缀表达式阅读 2606
-
Java 查看诊断 JVM 的命令行参数阅读 218
-
Vue props 自定义属性阅读 639
-
PHP 时间加减阅读 2249
-
ThinkPHP5 设置数据库长连接阅读 4407
-
Spring Boot jar 包执行报 no main manifest attribute 错误阅读 2146
-
Java 中 Thread 的 join 方法阅读 1917
-
The temporary upload location [xxxRoot] is not valid阅读 2703