简体   繁体   English

从 Java servlet 中的 POST 请求获取请求负载

[英]Getting request payload from POST request in Java servlet

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.我有一个 javascript 库,它向我的 Java servlet 发送 POST 请求,但在doPost方法中,我似乎无法获取请求有效负载的内容。 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.在 chrome Developer Tools 中,所有内容都在 headers 选项卡的 Request Payload 部分中,内容就在那里,我知道 POST 正在被 doPost 方法接收,但它只是空白。

For the HttpServletRequest object, what way can I get the data in the request payload?对于HttpServletRequest对象,我可以通过什么方式获取请求负载中的数据?

Doing request.getParameter() or request.getAttributes() both end up with no data执行request.getParameter()request.getAttributes()最终都没有数据

Simple answer:简单回答:
Use getReader() to read the body of the request使用 getReader() 读取请求正文

More info:更多信息:
There are two methods for reading the data in the body:读取body中的数据有两种方法:

  1. getReader() returns a BufferedReader that will allow you to read the body of the request. getReader()返回一个BufferedReader允许您读取请求的正文。

  2. getInputStream() returns a ServletInputStream if you need to read binary data.如果您需要读取二进制数据, getInputStream()返回一个ServletInputStream

Note from the docs: "[Either method] may be called to read the body, not both."文档中的注释:“可能会调用 [任一方法] 来读取正文,而不是同时调用两者。”

String payloadRequest = getBody(request);

Using this method使用这种方法

public static String getBody(HttpServletRequest request) throws IOException {

    String body = null;
    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;
            }
        }
    }

    body = stringBuilder.toString();
    return body;
}

You can use Buffer Reader from request to read您可以使用 Buffer Reader 从请求中读取

    // Read from request
    StringBuilder buffer = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
        buffer.append(line);
        buffer.append(System.lineSeparator());
    }
    String data = buffer.toString()

Java 8 streams Java 8 流

String body = request.getReader().lines()
    .reduce("", (accumulator, actual) -> accumulator + actual);

使用Apache Commons IO,您可以在一行中完成此操作。

IOUtils.toString(request.getReader())

如果正文的内容是 Java 8 中的字符串,您可以执行以下操作:

String body = request.getReader().lines().collect(Collectors.joining());

If you are able to send the payload in JSON, this is a most convenient way to read the playload:如果您能够以 JSON 格式发送有效负载,这是读取播放负载的最便捷方式:

Example data class:示例数据类:

public class Person {
    String firstName;
    String lastName;
    // Getters and setters ...
}

Example payload (request body):示例负载(请求正文):

{ "firstName" : "John", "lastName" : "Doe" }

Code to read payload in servlet (requires com.google.gson.*):在 servlet 中读取有效负载的代码(需要 com.google.gson.*):

Person person = new Gson().fromJson(request.getReader(), Person.class);

That's all.就这样。 Nice, easy and clean.漂亮,简单,干净。 Don't forget to set the content-type header to application/json.不要忘记将内容类型标头设置为 application/json。

Using Java 8 try with resources:使用 Java 8 尝试使用资源:

    StringBuilder stringBuilder = new StringBuilder();
    try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
        char[] charBuffer = new char[1024];
        int bytesRead;
        while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
            stringBuilder.append(charBuffer, 0, bytesRead);
        }
    }

You only need你只需要

request.getParameterMap() request.getParameterMap()

for getting the POST and GET - Parameters.用于获取 POST 和 GET - 参数。

The Method returns a Map<String,String[]> .该方法返回一个Map<String,String[]>

You can read the parameters in the Map by您可以通过以下方式读取 Map 中的参数

Map<String, String[]> map = request.getParameterMap();
//Reading the Map
//Works for GET && POST Method
for(String paramName:map.keySet()) {
    String[] paramValues = map.get(paramName);

    //Get Values of Param Name
    for(String valueOfParam:paramValues) {
        //Output the Values
        System.out.println("Value of Param with Name "+paramName+": "+valueOfParam);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM