6

I am working on a project where i request an api to post an item details. The following is my code where i tried to insert a body itemstr using HttpRequest

 public void test(){
        newItem item = new newItem(12,12,12,21,"waiwai");
        JSONObject itemobj = new JSONObject(item);
        String itemStr = itemobj.toString();
        System.out.println(itemStr);
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:3001/postMongo")).POST(HttpRequest.BodyPublishers.ofString(itemStr)).build();

    }

this is my newItem class

public class newItem {
    int id,wholesaleRate,SellingPrice,stock;
    String name;

    public int getStock() {
        return stock;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getWholesaleRate() {
        return wholesaleRate;
    }

    public void setWholesaleRate(int wholesaleRate) {
        this.wholesaleRate = wholesaleRate;
    }

    public int getSellingPrice() {
        return SellingPrice;
    }

    public void setSellingPrice(int sellingPrice) {
        SellingPrice = sellingPrice;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public newItem(int id, int wholesaleRate, int sellingPrice, int stock, String name) {
        this.id = id;
        this.wholesaleRate = wholesaleRate;
        this.SellingPrice = sellingPrice;
        this.stock = stock;
        this.name = name;
    }
}

I am trying to post the itemStr as a body to a restful API that i run locally. I could retrieve using the GET request but could not post.

John Pachuau
  • 73
  • 1
  • 1
  • 6

2 Answers2

9

OpenJDK has posted a recipe for bridging the new Java 11 HTTP client and Jackson: http://openjdk.java.net/groups/net/httpclient/recipes.html#jsonPost

ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper
      .writerWithDefaultPrettyPrinter()
      .writeValueAsString(map);

HttpRequest request = HttpRequest.newBuilder(uri)
      .header("Content-Type", "application/json")
      .POST(BodyPublishers.ofString(requestBody))
      .build();

return HttpClient.newHttpClient()
      .sendAsync(request, BodyHandlers.ofString())
      .thenApply(HttpResponse::statusCode)
      .thenAccept(System.out::println);

Hopefully Jackson will soon implement BodyPublisher itself instead of having to serialize to a string first...

J. Dimeo
  • 262
  • 2
  • 10
0

I recommend using GSON

UserEntity user = new UserEntity();
user.setUserName("UserName");
user.setUserAge(18);

Gson gson = new Gson();
String jsonStr = gson.toJson(user);

Please refer to this post to convert your object to JSON: Converting Java objects to JSON with Jackson

Hassen Ch.
  • 1,693
  • 18
  • 31