【分享】RestTemplate 请求接口,传json格式参数

avatar

服务端使用的是 springboot搭建的接口服务,代码如下

@PostMapping("/test")
public Object test(@RequestBody TestUser user) {
    System.out.println(user.toString());
    System.out.println(user.getUsername());
    return "success";
}

测试实体类

@Data
@ToString
public class TestUser {

	private String username;

	private TestAddress address;

}
@Data
@ToString
public class TestAddress {

	private String address;
}

测试代码

@Test
void contextLoads() {
    RestTemplate restTemplate = new RestTemplate();
    
    // 使用JSONObject类构建json格式数据
//		JSONObject jsonObject = new JSONObject();
//		jsonObject.put("username", "tomcat");
//
//		JSONObject addressJsonObject = new JSONObject();
//		addressJsonObject.put("address", "Shanghai");
//
//		jsonObject.put("address", addressJsonObject);

    // 直接使用实体类构建,然后转成json字符串
    TestAddress address = new TestAddress();
    address.setAddress("Beijing");
    TestUser user = new TestUser();
    user.setAddress(address);
    user.setUsername("jetty");

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    // HttpEntity<String> entity = new HttpEntity<>(jsonObject.toString(), headers);
    HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(user), headers);
    ResponseEntity<String> postForEntity = restTemplate.postForEntity("http://localhost:8080/test", entity,
            String.class);

    System.out.println(postForEntity.getBody());
}

打印结果

TestUser(username=tomcat, address=TestAddress(address=Shanghai))
tomcat
TestUser(username=jetty, address=TestAddress(address=Beijing))
jetty
目前还没有回答,快来帮帮TA吧!
添加一条评论 请尽量发布对他人有帮助的评论

登录后可发布评论

登录 | Github登录