由于我的Java基礎(chǔ)不是很好,加上很少寫代碼,所以最近在寫http接口測試的過程中,遇到了一些傳參的問題,調(diào)試了很久。在此把有結(jié)論的傳參類型記錄一下,便于后續(xù)回顧。
一:固定類型的參數(shù)傳入

傳入固定的invoice類型
剛開始的時(shí)候,我把下面的【0:2】當(dāng)做一個(gè)Map類型去處理的,代碼如下:
Map<String, String> invoiceType = new HashMap<>();
invoiceType.put("0", "2");
List<Map<String, String>> invoiceTypeList = new ArrayList<>();
invoiceTypeList.add(invoiceType);
但是調(diào)試的時(shí)候發(fā)現(xiàn)仍是報(bào)400錯(cuò)誤,才意識到【2】是一個(gè)固定的類型,傳String即可,0只是一個(gè)默認(rèn)的排序,可以忽略不處理的 ,所以修改了一下代碼如下:
String invoiceType = "2";
List<String> invoiceTypeList = new ArrayList<>();
invoiceTypeList.add(invoiceType);
然后就調(diào)試成功啦。
二:參數(shù)是多個(gè)list
參數(shù)如下:

要把各個(gè)list拆分,分別傳參:
//先定義一個(gè)Map類型的參數(shù)params
Map<String, Object> params = new HashMap<>();
//定義params參數(shù)下的accountDocument參數(shù)類型
Map<String, Object> accountDocument = new HashMap<>();
//給accountDocument傳參
accountDocument.put("accountSetId", "182");
...
//定義params參數(shù)下的entryDtoList參數(shù)類型
List<Map<String, Object>> entryDtoList = new ArrayList<>();
//定義entryDtoList參數(shù)下的第一個(gè)參數(shù),即參數(shù)0
Map<String, Object> entryDto1 = new HashMap<>();
//定義參數(shù)0下的參數(shù):
entryDto1.put("unit", null);
entryDto1.put("fcurCode", null);
Map<String, String> accountEntry1 = new HashMap<>();
//根據(jù)每層定義的參數(shù)分別傳參,一層一層嵌套即可
entryDto1.put("accountEntry", accountEntry1);
entryDtoList.add(entryDto1);
//定義entryDtoList參數(shù)下的第二個(gè)參數(shù),即參數(shù)1
Map<String, Object> entryDto2 = new HashMap<>();
entryDto2.put("unit", null);
entryDto2.put("fcurCode", null);
Map<String, String> accountEntry2 = new HashMap<>();
//根據(jù)每層定義的參數(shù)分別傳參,一層一層嵌套即可
entryDto2.put("accountEntry", accountEntry2);
entryDtoList.add(entryDto2);
//最后把entryDtoList參數(shù)傳回到params參數(shù)中,完成傳參
params.put("entryDtoList", entryDtoList);
表單類型的參數(shù)Form

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("remark", "測試");
感想
在http接口中傳參,有兩個(gè)要點(diǎn)。
1.搞清楚要傳入?yún)?shù)的類型
目前主要用到的類型是:String/Object/Map/List
Map傳值:Map<String,String>、Map<String,Object>
List傳值:List<String>、List<Map<String, String>>
2.分清參數(shù)的層次,逐層傳參
詳見【二:參數(shù)是多個(gè)list】