如何在java中从HttpServletRequest检索原始帖子数据 [英] How to retrieve raw post data from HttpServletRequest in java

查看:20
本文介绍了如何在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 get JSON POST data 并使用 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("
");
        } 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():

The request body is available as byte stream by HttpServletRequest#getInputStream():

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

作为字符流由 HttpServletRequest#getReader():

Or as character stream by HttpServletRequest#getReader():

Reader body = request.getReader();
// ...

请注意,您只能阅读一次.客户端不会多次重新发送相同的请求.调用 getParameter() 等也会隐式读取它.如果您稍后需要分解参数,则必须将主体存储在某处并自行处理.

Note that you can read it only once. The client ain't going to resend the same request multiple times. Calling getParameter() and so on will implicitly also read it. If you need to break down parameters later on, you've got to store the body somewhere and process yourself.

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

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