缓冲读取器返回 Null

发布于 2024-11-28 23:13:28 字数 616 浏览 2 评论 0原文

您好,我像这样向服务器发送 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

虚拟世界 2024-12-05 23:13:28

因为你已经到达了流的尽头。

来自 JavaDocs:

返回:包含该行内容的字符串,不包括任何内容
行终止字符,如果流结束已结束则为 null
达到

很可能返回空结果,那么问题就出在其他地方。我不知道 AJAX 请求是作为请求正文发送还是作为 POST 参数发送。使用 request.getParameter("json") 可能会有所帮助,但首先检查 LiveHttpHeaders,您的浏览器如何对请求进行编码以及哪个参数名称绑定到数据。在这种情况下,您根本不必使用 readline。

Because you reached the end of the stream.

From the JavaDocs:

Returns: A String containing the contents of the line, not including any
line-termination characters, or null if the end of the stream has been
reached

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.

不即不离 2024-12-05 23:13:28

我测试了一下,你使用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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文