简体   繁体   中英

How to send json Object in http post request in Java

I am trying to send below code as Json array in post request, Here is my Json:

        *{
            "date": "2019-01-01",
            "source": {
                "type": "calendar"
            },
            "device": {
                "type": "mobile"
            }
        }*
    Here is my code
    
        
    
    **JSONArray array1 = new JSONArray();
        JSONArray array2 = new JSONArray();
        JSONObject obj = new JSONObject();
        JSONObject obj2 = new JSONObject();
        JSONObject obj3 = new JSONObject();
    
        obj.put("date","2019-01-01");
        obj2.put("type","calendar");
        obj3.put("type","mobile");
        array1.put(obj2.toString());
    
        obj.put("source",array1.toString());
        obj.put("device",array2.toString());**
    

Now i want to send this object in post request. How do i do that?

HttpRequest request = HttpRequest.newBuilder().POST(obj) 
    

here how can i send the "obj" in post request

Using MockMvc, as an example, will be like this:

[...]

ObjectMapper objectMapper;

MvcResult result = 
            mockMvc
                .perform(post(URL)
                .headers(headers)
                .content(objectMapper.writeValueAsString(MY OBJECT)))
                .andDo(print())
                .andExpect(status().isCreated())
                .andReturn();

I've used this example code in my tests project. I guess ObjectMapper will help you: :)

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