目录
-
通过ServletInputStream读取http请求传入的数据
- 1. 使用ServletInputStream获取传入的数据
- 2. 通过ServletInputStream获取的是String类型
-
ServletInputStream类
- ServletInputStream类提供流从请求对象读取二进制数据
通过ServletInputStream读取http请求传入的数据
问题提出:使用nodejs的http向java web发送请求,java后台未收到数据。
1. 使用ServletInputStream获取传入的数据
?| 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 |
/**
* 增加数据
* @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
?| 1 2 |
JSONObject jsonObj = JSONObject.fromObject(strcont);
System.out.println(jsonObj.getString("module"));
|
需要的jar包:

ServletInputStream类
ServletInputStream类提供流从请求对象读取二进制数据
如图像等。这是一个抽象类。
ServletRequest接口的getInputStream()方法返回ServletInputStream类的实例。
所以可以得到:
?| 1 |
ServletInputStream sin=request.getInputStream();
|
Java
- ServletInputStream类的方法
- ServletInputStream类中只定义了一种方法
int readLine(byte[] b, int off, int len) - 它读取输入流。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/swl979623074/article/details/52992733








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。