Java 从 HttpServletRequest 获取原始请求字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1342213/
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-08-12 08:26:42  来源:igfitidea点击:

Get the Raw Request String from HttpServletRequest

javajsfservlets

提问by Jaime Garcia

Is it possible to get the raw HTTP Request from the HttpServletRequest object? I want to see the raw request as a String if at all possible.

是否可以从 HttpServletRequest 对象获取原始 HTTP 请求?如果可能的话,我想将原始请求视为字符串。

I need to get the full text of the request, in this case it's a POST request, so the URL doesn't help. It's also part of a multi-part form, so I can't just call the "getParameterNames()" or "getParameterValues()".

我需要获取请求的全文,在这种情况下它是一个 POST 请求,所以 URL 没有帮助。它也是多部分表单的一部分,所以我不能只调用“getParameterNames()”或“getParameterValues()”。

Thank you,

谢谢,

采纳答案by McDowell

Sounds like you need a servlet filter. There is no standard way to handle multipart/form-data, so you'll have to take care to cache this data appropriately when wrapping the HttpServletRequest.

听起来您需要一个servlet 过滤器。没有处理 的标准方法multipart/form-data,因此在包装 HttpServletRequest时,您必须注意适当地缓存此数据。

回答by Puran

or if you can write some interceptor to convert the parameter names and values to string format object and set it in request context, or filter is a good idea too.

或者如果您可以编写一些拦截器将参数名称和值转换为字符串格式对象并将其设置在请求上下文中,或者过滤器也是一个好主意。

回答by Chris J

Well, it sounds like you are doing some sort of troubleshooting. Why not just drop the multi-part form component while you are looking at the raw form data. You can use the following JSP snippet to construct the form data.

嗯,听起来你正在做某种故障排除。为什么不在查看原始表单数据时删除多部分表单组件。您可以使用以下 JSP 片段来构造表单数据。

<%
Enumeration en = request.getParameterNames();
String str = "";
while(en.hasMoreElements()){
   String paramName = (String)en.nextElement();
   String paramValue = request.getParameter(paramName);
   str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
}
if (str.length()>0)
   str = str.substring(1);
%>

回答by monchote

You can read the raw HTTP request by doing:

您可以通过执行以下操作读取原始 HTTP 请求:

ServletInputStream in = request.getInputStream();

and then use the regular readmethods of the InputStream.

然后使用readInputStream的常规方法。

Hope that helps.

希望有帮助。

回答by PbxMan

If you want to get the whole request to a String you can do it with one line of code using the apache IOUtils library.

如果您想将整个请求发送到一个字符串,您可以使用 apache IOUtils 库通过一行代码来完成。

String myString = org.apache.commons.io.IOUtils.toString(request.getInputStream());