目录 通过ServletInputStream读取http请求传入的数据 1. 使用ServletInputStream获取传入的数据 2. 通过ServletInputStream获取的是String类型 ServletInputStream类 ServletInputStream类提供流从请求对象读取二进
          目录
- 通过ServletInputStream读取http请求传入的数据
- 1. 使用ServletInputStream获取传入的数据
- 2. 通过ServletInputStream获取的是String类型
- ServletInputStream类
- ServletInputStream类提供流从请求对象读取二进制数据
通过ServletInputStream读取http请求传入的数据
问题提出:使用nodejs的http向java web发送请求,java后台未收到数据。
1. 使用ServletInputStream获取传入的数据
/**
 * 增加数据 
 * @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类提供流从请求对象读取二进制数据
如图像等。这是一个抽象类。
ServletRequest接口的getInputStream()方法返回ServletInputStream类的实例。
所以可以得到:
ServletInputStream sin=request.getInputStream();
Java
- ServletInputStream类的方法
- ServletInputStream类中只定义了一种方法
int readLine(byte[] b, int off, int len) - 它读取输入流。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。
