使用HttpClient模拟访问带有嵌套对象参数的接口

    项目中涉及到外部服务调用时,会使用到postman来模拟测试,例如一个接口如下:

@RequestMapping("/test")
public void test(@RequestBody User user){

}

    User类的属性包括id、name、age三个属性,那么当你使用postman调用接口时,就可以使用这三个参数传进去,它会自动映射到User对象中,或者使用httpclient(例如用BasicNameValuePair将参数集放到entity中)也可以达到这种效果。

     那如果是嵌套对象,比如我有一个类如下:

public class People implements Serializable {
    private List<User> userList;
    private static final long serialVersionUID = 1L;

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

}

   相应的接口如下:

@RequestMapping("/test")
public void test(@RequestBody People people){

}

   这时再使用postman就不太好使了,我不确定postman能把参数映射进子对象吗,反正用httpclient可以这么做:

        // 先定义接口需要的参数对象   
        People people=new People();

        List<User> list=new ArrayList<>();
        for(int i=0;i<3;i++) {

            User user=new User();
            user.setUserId(i);
            user.setName("user"+i);
            user.setAge(i);
            
            list.add(user);
            
        }
        people.setUserList(list);   
  
  // 然后就构造httpclient对象
  CloseableHttpClient httpclient = HttpClients.createDefault();
  HttpPost httpPost = new HttpPost(uri);
  // 在传送复杂嵌套对象时,一定要把对象转成json字符串,我这里实用的是alibaba.fastjson,当然你也可以使用其他的json工具
  String a=JSON.toJSONString(people);

  StringEntity requestEntity=new StringEntity(a,"utf-8");
  requestEntity.setContentEncoding("UTF-8");
  httpPost.setEntity(requestEntity); 
  httpPost.addHeader("Content-Type","application/json");
  CloseableHttpResponse response2 = httpclient.execute(httpPost);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值