如何通過ServletInputStream讀取http請求傳入的數(shù)據(jù)
通過ServletInputStream讀取http請求傳入的數(shù)據(jù)
問題提出:使用nodejs的http向java web發(fā)送請求,java后臺未收到數(shù)據(jù)。
1. 使用ServletInputStream獲取傳入的數(shù)據(jù)
/** * 增加數(shù)據(jù) * @param module * @param function * @param system * @param platform * @param time * @param status * @return ModelAndView * @throws IOException */ @RequestMapping("/insertOne") public ModelAndView insertOne(HttpServletRequest req) throws IOException { ServletInputStream ris = req.getInputStream(); StringBuilder content = new StringBuilder(); byte[] b = new byte[1024]; int lens = -1; while ((lens = ris.read(b)) > 0) { content.append(new String(b, 0, lens)); } String strcont = content.toString();// 內(nèi)容 JSONObject jsonObj = JSONObject.fromObject(strcont); DBObject obj = new BasicDBObject(); obj.put("module", jsonObj.getString("module")); obj.put("function", jsonObj.getString("function")); obj.put("system", jsonObj.getString("system")); obj.put("platform", jsonObj.getString("platform")); obj.put("time", jsonObj.getString("time")); obj.put("status", jsonObj.getString("status")); Map<String, Object> map = new HashMap<String, Object>(); int len = ((DBManager) conn).insertOne(obj); map.put("status", (len == 0)?("SUCCESS"):("ERROR")); return MVC.toString(map); }
2. 通過ServletInputStream獲取的是String類型
使用時(shí)需要轉(zhuǎn)化成JSON
JSONObject jsonObj = JSONObject.fromObject(strcont); System.out.println(jsonObj.getString("module"));
需要的jar包:
ServletInputStream類
ServletInputStream類提供流從請求對象讀取二進(jìn)制數(shù)據(jù)
如圖像等。這是一個(gè)抽象類。
ServletRequest接口的getInputStream()方法返回ServletInputStream類的實(shí)例。
所以可以得到:
ServletInputStream sin=request.getInputStream();
Java
- ServletInputStream類的方法
- ServletInputStream類中只定義了一種方法
int readLine(byte[] b, int off, int len) - 它讀取輸入流。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章

java實(shí)現(xiàn)Dijkstra最短路徑算法

Java中OAuth2.0第三方授權(quán)原理與實(shí)戰(zhàn)

Java類之間的關(guān)系圖_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

SpringBoot Nacos實(shí)現(xiàn)自動(dòng)刷新