通過ServletInputStream讀取http請求傳入的數(shù)據(jù)
問題提出:使用nodejs的http向java web發(fā)送請求,java后臺未收到數(shù)據(jù)。
1. 使用ServletInputStream獲取傳入的數(shù)據(jù)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
/** * 增加數(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類型
使用時需要轉(zhuǎn)化成JSON
1
2
|
JSONObject jsonObj = JSONObject.fromObject(strcont); System.out.println(jsonObj.getString( "module" )); |
需要的jar包:
ServletInputStream類
ServletInputStream類提供流從請求對象讀取二進(jìn)制數(shù)據(jù)
如圖像等。這是一個抽象類。
ServletRequest接口的getInputStream()方法返回ServletInputStream類的實(shí)例。
所以可以得到:
1
|
ServletInputStream sin=request.getInputStream(); |
Java
- ServletInputStream類的方法
- ServletInputStream類中只定義了一種方法
int readLine(byte[] b, int off, int len) - 它讀取輸入流。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/swl979623074/article/details/52992733