时间:2022-10-30 11:07:53 | 栏目:JAVA代码 | 点击:次
问题提出:使用nodejs的http向java web发送请求,java后台未收到数据。
/**
* 增加数据
* @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);
}
使用时需要转化成JSON
JSONObject jsonObj = JSONObject.fromObject(strcont);
System.out.println(jsonObj.getString("module"));
需要的jar包:

如图像等。这是一个抽象类。
ServletRequest接口的getInputStream()方法返回ServletInputStream类的实例。
所以可以得到:
ServletInputStream sin=request.getInputStream();
Java
int readLine(byte[] b, int off, int len) - 它读取输入流。