简体   繁体   English

无法获取 POST 请求正文

[英]Failing to get a POST request body

I'm trying to get a JSON from the body of a request post method (using insomnia/postman), but I have no progress doing this.我正在尝试从请求发布方法的主体中获取 JSON(使用失眠/邮递员),但我在这方面没有进展。 I did a class called PlayerData, which have only one attribute (userId).我做了一个名为 PlayerData 的 class,它只有一个属性(userId)。 I'm using Jackson library to use readValue method, in order to map my json body to my java class PlayerData. I'm using Jackson library to use readValue method, in order to map my json body to my java class PlayerData. To be able to see what is happening, I been have putting a print log and breakpoints to debug what could be, but for some reason, both of them are skipped by my code.为了能够看到正在发生的事情,我已经放置了一个打印日志和断点来调试可能发生的事情,但由于某种原因,我的代码都跳过了它们。 I don't return a response, because in this case I don't want to.我没有回复,因为在这种情况下我不想回复。 The idea here is only to set a instance of PlayerData with userId from body request, with no need to persist data on disk.这里的想法只是从正文请求中设置一个带有 userId 的 PlayerData 实例,而无需将数据保存在磁盘上。

PlayerData.class玩家数据.class

package com.pipa.api;

import lombok.Builder;
import lombok.Value;

@Value
@Builder
public class PlayerData {
  private Integer userId;
}

Application.java应用.java

package com.pipa.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class Application {

    private static ObjectMapper objectMapper;

    public static void main(String[] args) throws IOException {
        int serverPort = 8000;
        HttpServer server = HttpServer.create(new InetSocketAddress(serverPort), 0);

        server.createContext("/post", (exchange -> {
            if ("POST".equals(exchange.getRequestMethod())) {
                PlayerData playerData = objectMapper.readValue(exchange.getRequestBody(), PlayerData.class);
                System.out.println("this print never appear");
            } else {
                exchange.sendResponseHeaders(405, -1); // 405 Method Not Allowed
            }

            exchange.close();
        }));

        server.setExecutor(null); // creates a default executor
        server.start();
    }
}

There is something happening at the line objectMapper.readValue(exchange.getRequestBody(), PlayerData.class); objectMapper.readValue(exchange.getRequestBody(), PlayerData.class);行发生了一些事情。

exchange.getRequestBody() returns an instance of InputStream. exchange.getRequestBody()返回 InputStream 的一个实例。 I tried to convert the InputStream to string and it worked fine.我试图将 InputStream 转换为字符串,它工作正常。 I also used net.sf.json.JSONObject to parse the JSON string and then converted it into an object of class PlayerData.我还使用了net.sf.json.JSONObject来解析JSON字符串,然后将其转换为object的ZA2F212ED4F8EBC2CBB1. If you use this approach the code execution goes to the last print statement.如果您使用这种方法,代码执行将转到最后一个打印语句。

            InputStream inputStream = exchange.getRequestBody();
            StringWriter writer = new StringWriter();
            IOUtils.copy(inputStream, writer );
            String theString = writer.toString();
            System.out.println(theString);
            JSONObject jsonObject = JSONObject.fromObject(theString);
            PlayerData pd = (PlayerData) JSONObject.toBean(jsonObject, PlayerData.class);
            System.out.println(pd.toString());

This is just a workaround as I still don't understand the reason behind the issue with objectMapper .这只是一种解决方法,因为我仍然不明白objectMapper问题背后的原因。

There are 2 issues with the code.代码有2个问题。

  1. private static ObjectMapper objectMapper; is never initialized.永远不会被初始化。 Therefore you will get NullPointerException.因此你会得到 NullPointerException。 Try private static ObjectMapper objectMapper = new ObjectMapper();尝试private static ObjectMapper objectMapper = new ObjectMapper();

  2. Using Lombok and Jackson, you may need to make changes as mentioned in this link使用 Lombok 和 Jackson,您可能需要按照链接中的说明进行更改

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

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