java 如何使用 RESTEasy 访问 HTTP 请求的正文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12617740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:34:46  来源:igfitidea点击:

How to access HTTP request's body with RESTEasy

javahttprestresteasy

提问by Raffo

I'm looking for a way to directly access the body of the HTTP request. In fact, in my code I receive different parameters in the body and I don't know in advance exactly what I will receive. Moreover I want to be as flexible as possible: I'm dealing with different requests that can vary and I want to handle them in a single method for each type of request (GET, POST, ... ). Is there a way to handle this level of flexibility with RESTEasy? Should I switch to something else?

我正在寻找一种直接访问 HTTP 请求正文的方法。事实上,在我的代码中,我在正文中收到了不同的参数,我事先并不确切知道我将收到什么。此外,我希望尽可能灵活:我正在处理可能会有所不同的不同请求,并且我希望针对每种类型的请求(GET、POST、...)以单一方法处理它们。有没有办法用 RESTEasy 处理这种级别的灵活性?我应该换别的吗?

采纳答案by Pritam Barhate

As per the code given in this answeryou can access the HTTPServletRequest Object.

根据此答案中给出的代码,您可以访问 HTTPServletRequest 对象。

Once you have HTTPServletRequest object you should be able access the request body as usual. One example can be:

拥有 HTTPServletRequest 对象后,您应该可以像往常一样访问请求正文。一个例子可以是:

String requestBody = "";
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
    InputStream inputStream = request.getInputStream();
    if (inputStream != null) {
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        char[] charBuffer = new char[128];
        int bytesRead = -1;
        while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
            stringBuilder.append(charBuffer, 0, bytesRead);
        }
    } else {
        stringBuilder.append("");
    }
} catch (IOException ex) {
    throw ex;
} finally {
    if (bufferedReader != null) {
        try {
            bufferedReader.close();
        } catch (IOException ex) {
            throw ex;
        }
    }
}
requestBody = stringBuilder.toString();