如何通過ServletInputStream讀取http請求傳入的數(shù)據(jù)
更新時間:2021年10月26日 10:44:33 作者:swlws>_>
這篇文章主要介紹了如何通過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();// 內容 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類型
使用時需要轉化成JSON
JSONObject jsonObj = JSONObject.fromObject(strcont); System.out.println(jsonObj.getString("module"));
需要的jar包:
ServletInputStream類
ServletInputStream類提供流從請求對象讀取二進制數(shù)據(jù)
如圖像等。這是一個抽象類。
ServletRequest接口的getInputStream()方法返回ServletInputStream類的實例。
所以可以得到:
ServletInputStream sin=request.getInputStream();
Java
- ServletInputStream類的方法
- ServletInputStream類中只定義了一種方法
int readLine(byte[] b, int off, int len) - 它讀取輸入流。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。