spring—如何在java中发送http post请求中的json对象

eh57zj3b  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(282)

我试图在post请求中以json数组的形式发送以下代码,以下是我的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());**

现在我想在post请求中发送这个对象。我该怎么做?

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

在这里,我如何发送“obj”的邮政请求

3pvhb19x

3pvhb19x1#

以mockmvc为例,如下所示:

[...]

ObjectMapper objectMapper;

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

我在我的测试项目中使用了这个示例代码。我想objectmapper会帮你的!:)

相关问题