1.近来在开发过程中使用RestTemplate调用服务接口,参数是集合,记录下过程
List<OnbuyInventoryImport> parcelInfoList = excel.getDataList(OnbuyInventoryImport.class); //设置请求头 HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); //将list转换为json String json = gson.toJson(parcelInfoList); HttpEntity<String> formEntity = new HttpEntity<String>(json, headers); //调用服务接口,此时的请求参数存放于body中。服务端接受参数解析body即可。 result = restTemplate.postForObject(ONBUY_URL+"/uploadAmazonOrderExcel", formEntity, JsonResult.class);
2.服务端接口接受参数方法
@ApiOperation(value = "订单导入", notes = "type:导入类型:1为平台模板导入 2为标准模板导入") @PostMapping(value = "/onbuy/uploadAmazonOrderExcel") public JsonResult amazeOrderImport( HttpServletRequest httpServletRequest) throws Exception { JsonResult<Map<String, Integer>> result = new JsonResult<Map<String, Integer>>( ResultCode.SUCCESS); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); //解析body获得参数 String tmpStr= null; byte[] content = new byte[0]; content = IOUtils.toByteArray(httpServletRequest.getInputStream()); tmpStr = new String(content,"UTF-8"); logger.info("请求参数:"+tmpStr); //将参数解析为自己对应的集合 List<OnbuyInventoryImport> parcelInfoList = gson.fromJson(tmpStr,new TypeToken<List<OnbuyInventoryImport>>() {}.getType()); }