1. 程式人生 > >使用HttpClient模擬訪問帶有巢狀物件引數的介面

使用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);