缓冲读取器返回 Null
您好,我像这样向服务器发送 ajax 调用
$.ajax({
type: 'POST',
url: "...",
dataType:'json',
data:JSON.stringify(contact),
success:function(){
alert("success")
}
在服务器上,我处理此请求并尝试从请求中读取 json 对象,如下所示。
StringBuilder sb = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new
InputStreamReader(request.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
}
但 br.readLine() 返回 null。知道为什么会发生吗?
Hi i send an ajax call to server like this
$.ajax({
type: 'POST',
url: "...",
dataType:'json',
data:JSON.stringify(contact),
success:function(){
alert("success")
}
At server i handle this request and trying to read the json object from request like this.
StringBuilder sb = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new
InputStreamReader(request.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
}
but br.readLine() returns null. Any idea why it happens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为你已经到达了流的尽头。
来自 JavaDocs:
很可能返回空结果,那么问题就出在其他地方。我不知道 AJAX 请求是作为请求正文发送还是作为 POST 参数发送。使用 request.getParameter("json") 可能会有所帮助,但首先检查 LiveHttpHeaders,您的浏览器如何对请求进行编码以及哪个参数名称绑定到数据。在这种情况下,您根本不必使用 readline。
Because you reached the end of the stream.
From the JavaDocs:
Very likely an empty result is returned, the problem is somewhere else then. I don't know if the AJAX request is send as a body of the request, or as a POST parameter. Use request.getParameter("json") instead might help, but check with LiveHttpHeaders first, how your browser encodes the request and which parameter name is bound to the data. In this case you don't have to work with readline at all.
我测试了一下,你使用HTTP请求InputStream的方式是没有问题的。 “contact”元素很可能在请求时未定义。因此它被转换为空 JSON 字符串。
尝试向“数据”字段添加一些固定文本,您应该会看到它在服务器端工作。
I tested it and there is no problem with how you use the HTTP request InputStream. The 'contact' element is most likely undefined at the time of the request. Therefore it is converted to an empty JSON string.
Try adding some fixed text to the 'data' field and you should see it working on server side.