Spring Boot 将 InputStream 输入流转换为 String

Spring Boot About 1,214 words

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();
    }

}
Views: 2,362 · Posted: 2023-01-23

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh