讀取InputStream 中的內容
/**
* 讀取 InputStream 到 String字符串中
*/
public static String readStream(InputStream in) {
try {
//<1>創建字節數組輸出流,用來輸出讀取到的內容
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//<2>創建緩存大小
byte[] buffer = new byte[1024]; // 1KB
//每次讀取到內容的長度
int len = -1;
//<3>開始讀取輸入流中的內容
while ((len = in.read(buffer)) != -1) { //當等於-1說明沒有數據可以讀取了
baos.write(buffer, 0, len); //把讀取到的內容寫到輸出流中
}
//<4> 把字節數組轉換為字符串
String content = baos.toString();
//<5>關閉輸入流和輸出流
in.close();
baos.close();
//<6>返回字符串結果
return content;
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}