跳至主要內容

http请求参数

chanchaw小于 1 分钟javaspring

restful API 一般接受实体类对象作为参数,也可以接受 Map 对象。这两种参数 springboot 会自动反序列化为对象后再使用。对象类型、MAP类型的API如下:

public JsonResult save(@RequestBody AssBaseSimple record) {
        return JsonResult.ok(service.save(record));
}

调用方法如下

// 为调用接口准备URL和参数
Vue3userDTO record = new Vue3userDTO();
record.setName("j");
String url = "/assBusiTodo/selectAll";

String post = postJsonParam(url, record);
System.out.println(post);


// 方法内先将参数 params 序列化再使用
private String postJsonParam(String url, Object params) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
    java.lang.String requestJson = ow.writeValueAsString(params);

    MockHttpServletResponse res = mockMvc.perform(MockMvcRequestBuilders.post(url)//发送 get 请求
                                                  .contentType(MediaType.APPLICATION_JSON_UTF8).content(requestJson))// 发送的请求中带名称为 username 的参数
        .andExpect(MockMvcResultMatchers.status().isOk())// 要求返回200
        .andReturn().getResponse();

    res.setCharacterEncoding("UTF-8");
    return res.getContentAsString();
}

如果传递的是基本类型,API如下:

public JsonResult getByCategory(@RequestBody String category){
    return JsonResult.ok(service.getByCategory(category));
}

调用方法如下

String url = "/assBaseSimple/getByCategory";
String ret = postStringParam(url, "等级");
System.out.println(ret);

private String postStringParam(String url, String params) throws Exception {
    MockHttpServletResponse res = mockMvc.perform(MockMvcRequestBuilders.post(url)//发送 get 请求
                    .contentType(MediaType.APPLICATION_JSON_UTF8).content(params))// 发送的请求中带名称为 username 的参数
            .andExpect(MockMvcResultMatchers.status().isOk())// 要求返回200
            .andReturn().getResponse();

    res.setCharacterEncoding("UTF-8");
    return res.getContentAsString();
}