/**
* 将流中的内容转换为字符串,主要用于提取request请求的中requestBody
* @param in
* @param encoding
* @return
*/
public static String streamToString(InputStream in, String encoding){
// 将流转换为字符串
try {
StringBuffer sb = new StringBuffer();
byte[] b = new byte[1024];
for (int n; (n = in.read(b)) != -1;) {
sb.append(new String(b, 0, n, encoding));
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("提取 requestBody 异常", e);
}
}
/**
* 将流中的内容转换为字符串,主要用于提取request请求的中requestBody
* @param in
* @param encoding
* @return
*/
public static String streamToString(InputStream in, String encoding){
// 将流转换为字符串
try {
StringBuffer sb = new StringBuffer();
byte[] b = new byte[1024];
for (int n; (n = in.read(b)) != -1;) {
sb.append(new String(b, 0, n, encoding));
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("提取 requestBody 异常", e);
}
}
/**
* 将流中的内容转换为字符串,主要用于提取request请求的中requestBody
* @param in
* @param encoding
* @return
*/
public static String streamToString(InputStream in, String encoding){
// 将流转换为字符串
ByteArrayOutputStream bos = null;
try {
// 1.创建内存输出流,将读到的数据写到内存输出流中
bos = new ByteArrayOutputStream();
// 2.创建字节数组
byte[] arr = new byte[1024];
int len;
while(-1 != (len = in.read(arr))) {
bos.write(arr, 0, len);
}
// 3.将内存输出流的数据全部转换为字符串
return bos.toString(encoding);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("提取 requestBody 异常", e);
} finally {
if(null != bos) {
try {
// 其实这个内存输出流可关可不关,因为它的close方法里面没做任何操作。
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 将流中的内容转换为字符串,主要用于提取request请求的中requestBody
* @param in
* @param encoding
* @return
*/
public static String streamToString(InputStream in, String encoding){
// 将流转换为字符串
ByteArrayOutputStream bos = null;
try {
// 1.创建内存输出流,将读到的数据写到内存输出流中
bos = new ByteArrayOutputStream();
// 2.创建字节数组
byte[] arr = new byte[1024];
int len;
while(-1 != (len = in.read(arr))) {
bos.write(arr, 0, len);
}
// 3.将内存输出流的数据全部转换为字符串
return bos.toString(encoding);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("提取 requestBody 异常", e);
} finally {
if(null != bos) {
try {
// 其实这个内存输出流可关可不关,因为它的close方法里面没做任何操作。
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
原文:https://www.cnblogs.com/zeng1994/p/508b333a5ef0ae98c80a3e1ab7615ebd.html