简体   繁体   中英

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. I did a class called PlayerData, which have only one attribute (userId). 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.

PlayerData.class

package com.pipa.api;

import lombok.Builder;
import lombok.Value;

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

Application.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);

exchange.getRequestBody() returns an instance of InputStream. I tried to convert the InputStream to string and it worked fine. I also used net.sf.json.JSONObject to parse the JSON string and then converted it into an object of class PlayerData. 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 .

There are 2 issues with the code.

  1. private static ObjectMapper objectMapper; is never initialized. Therefore you will get NullPointerException. Try private static ObjectMapper objectMapper = new ObjectMapper();

  2. Using Lombok and Jackson, you may need to make changes as mentioned in this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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