1、流方法讀取
@RequestMapping(value = "/http/test", method = RequestMethod.POST)
public void getHttpBody(HttpServletRequest request) throws Exception {
String str = "";
// 通過http請求的req中獲取字節輸入流
InputStream is = request.getInputStream();
// 用此類的原因是緩沖區在數據寫入到字節數組中時會自動增長
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// 定義一個字節數組
byte[] bytes = new byte[1024];
// 遍歷輸入流
for (int length; (length=is.read(bytes)) != -1;) {
// 寫入到輸出流中
bos.write(bytes,0,length);
}
// 輸出流再轉換為字節數組
byte[] resBytes = bos.toByteArray();
// 字節轉換為字符串
str = new String(resBytes,"UTF-8");
// 關閉流
bos.close();
is.close();
System.out.println(str);
JSONObject json = JSON.parseObject(str);
String body = json.getString("Body");
System.out.println(body);
}
2、字符串方法獲取
@RequestMapping(value = "/string/test", method = RequestMethod.POST)
public void getHttpBodyByStr(HttpServletRequest request) throws Exception {
// 定義一個字符輸入流
BufferedReader br = null;
// 定義一個可變字符串 這里不考慮線程安全問題 所以用StringBuilder
StringBuilder sb = new StringBuilder("");
br = request.getReader();
String str;
while ((str = br.readLine()) != null){
sb.append(str);
}
br.close();
String resStr = sb.toString();
System.out.println(resStr);
JSONObject json = JSON.parseObject(resStr);
String body = json.getString("Body");
System.out.println(body);
}