javarestgsonunirest

Unirest inserts empty fields when doing a POST with json body, even if same body works elsewhere


I'm using unirest to do a post/put request using as body a string I get from gson's toJson method

        String entityJson = gson.toJson(entity);
        System.out.println(entityJson);

        HttpResponse<JsonNode> response = Unirest.post(http://localhost:8080/post/")
                .header("Accept", "application/json")
                .body(entityJson)
                .asJson();
        System.out.println(response.getBody().toPrettyString());

The response I get has all the fields of the entity empty, but when copying the printed string of entityJson and using it as a json body while doing the same post request through postman it works correctly with all the fields filled like in the entity


Solution

  • I resolved it by specifying a new header and inserting it into the headers field like so

        Map<String, String> headers = new HashMap<>();
        headers.put("accept", "application/json");
        headers.put("content-type", "application/json");
    
      HttpResponse<JsonNode> response = Unirest.post(http://localhost:8080/post/")
                .headers(headers)
                .body(entityJson)
                .asJson();