使用RestTemplate调用接口,传递参数是list处理。

1.近来在开发过程中使用RestTemplate调用服务接口,参数是集合,记录下过程

List 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 formEntity = new HttpEntity(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> result = new JsonResult>(
            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 parcelInfoList = gson.fromJson(tmpStr,new TypeToken>() {}.getType());
}

你可能感兴趣的:(使用RestTemplate调用接口,传递参数是list处理。)