如何从java中的HttpServletRequest检索原始发布数据 [英] How to retrieve raw post data from HttpServletRequest in java

查看:757
本文介绍了如何从java中的HttpServletRequest检索原始发布数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Java获取帖子数据。看起来它应该是最简单的事情之一吗?我的意思是,HttpServletRequest.getParameter必须做对吗?那么如何获得原始发布数据?

I'm trying to get the post data in Java. Seems like it should be one of the simplest things to do right? I mean, HttpServletRequest.getParameter has to do it right? So how can you get the raw post data?

我发现 HttpServletRequest获取JSON POST数据并使用Kdeveloper的代码从请求中提取发布数据。它有效,但有一个问题:我只能获得一次的帖子数据。

I found HttpServletRequest get JSON POST data and used Kdeveloper's code to pull the post data from a request. It works, but theres a catch: I can only get that post data once.

以下是我用Kdeveloper代码制作的方法:

Heres the method I made from Kdeveloper's code:

public static String getPostData(HttpServletRequest req) {
    StringBuilder sb = new StringBuilder();
    try {
        BufferedReader reader = req.getReader();
        reader.mark(10000);

        String line;
        do {
            line = reader.readLine();
            sb.append(line).append("\n");
        } while (line != null);
        reader.reset();
        // do NOT close the reader here, or you won't be able to get the post data twice
    } catch(IOException e) {
        logger.warn("getPostData couldn't.. get the post data", e);  // This has happened if the request's reader is closed    
    }

    return sb.toString();
}

之前我在这个方法结束时关闭了读者,但是这导致了方法在同一请求上多次运行时的异常。没有关闭它,没有异常发生,但该方法返回一个空字符串。

Previously I had closed the reader at the end of this method, but that caused exceptions when the method ran more than once on the same request. Without closing it, no exceptions happen, but the method returns an empty string.

老实说,应该只有一个暴露的req.getPostData()方法 - 没有人认为那会有用吗?

Honestly, there should just be an exposed req.getPostData() method - did no one think that would be useful?

那么如何编写这种方法使它始终返回正确的帖子数据呢?

So how can I write this method such that it always returns the correct post data?

推荐答案

请求正文可由 HttpServletRequest#getInputStream() #getReader()

The request body is available by HttpServletRequest#getInputStream() and #getReader().

InputStream body = request.getInputStream();
// ...

请注意,您只能阅读一次。客户端不会多次重发它。调用 getParameter()等等也会隐式地读取它。你必须将身体存放在某个地方并自己处理。

Note that you can read it only once. The client ain't going to resend it multiple times. Calling getParameter() and so on will implicitly also read it. You've got to store the body somewhere and process yourself.

这篇关于如何从java中的HttpServletRequest检索原始发布数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆