我是靠谱客的博主 忐忑棒棒糖,这篇文章主要介绍如何通过ServletInputStream读取http请求传入的数据,现在分享给大家,希望可以做个参考。

通过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) - 它读取输入流。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持靠谱客。

最后

以上就是忐忑棒棒糖最近收集整理的关于如何通过ServletInputStream读取http请求传入的数据的全部内容,更多相关如何通过ServletInputStream读取http请求传入内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(512)

评论列表共有 0 条评论

立即
投稿
返回
顶部