从 Java servlet 中的 POST 请求获取请求负载 [英] Getting request payload from POST request in Java servlet
问题描述
我有一个 javascript 库,它向我的 Java servlet 发送 POST 请求,但在 doPost
方法中,我似乎无法获取请求有效负载的内容.在 chrome Developer Tools 中,所有内容都在 headers 选项卡的 Request Payload 部分中,内容就在那里,我知道 POST 正在被 doPost 方法接收,但它只是空白.
I have a javascript library that is sending a POST request to my Java servlet, but in the doPost
method, I can't seem to get the contents of the request payload. In chrome Developer Tools, all the content is in the Request Payload section in the headers tab, and the content is there, and I know that the POST is being received by the doPost method, but it just comes up blank.
对于HttpServletRequest
对象,我可以通过什么方式获取请求负载中的数据?
For the HttpServletRequest
object, what way can I get the data in the request payload?
执行 request.getParameter()
或 request.getAttributes()
两者最终都没有数据
Doing request.getParameter()
or request.getAttributes()
both end up with no data
推荐答案
简单回答:
使用 getReader() 读取请求正文
Simple answer:
Use getReader() to read the body of the request
更多信息:
读取body中的数据有两种方法:
More info:
There are two methods for reading the data in the body:
getReader()
返回一个 BufferedReader 这将允许您读取请求的正文.
getReader()
returns a BufferedReader that will allow you to read the body of the request.
getInputStream()
返回一个 ServletInputStream 如果您需要读取二进制数据.
getInputStream()
returns a ServletInputStream if you need to read binary data.
文档中的注释:可以调用[任一方法] 来读取正文,而不是同时调用."
Note from the docs: "[Either method] may be called to read the body, not both."
这篇关于从 Java servlet 中的 POST 请求获取请求负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!