restTemplate 传递map

@Autowired
private RestTemplate restTemplate;
//通过restTemplate post传递map方法  接口返回一个int类型
public void longRangeTest(){
   HttpHeaders headers = new HttpHeaders();
   MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
    headers.setContentType(type);
   headers.add("Accept", MediaType.APPLICATION_JSON.toString());
   StringBuilder url = new StringBuilder("http://localhost:8889/longRangTest");
   Map,Object> map = merge.findById("590fe009d09e9833a46185c7");
   map.put("_id",map.get("_id").toString());
   map.put("_tableName","MergeCommunity");
   JSONObject jsonObj = JSONObject.fromObject(map);
   HttpEntity formEntity = new HttpEntity<>(jsonObj.toString(), headers);
   System.err.println("返回:"+restTemplate.postForObject(url.toString(), formEntity , int.class));

}

//接口action

@PostMapping("longRangTest")
public int longRangTest(@RequestBody Map,Object> map){
   return getSpiderService.updateDataMeta(map);
}

//实现代码

/***
 * @param entity
 * @return 0表示失败,1表示成功
 */
public int updateDataMeta(Map,Object> entity){
    try {
        if( entity.get("_tableName")==null) return 0;
        String tableName = entity.get("_tableName").toString();//表明
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(entity.get("_id")));
        Update update = new Update();
        Set set = entity.keySet();//将传递过来的一个map转换为update进行跟新
        for(String s : set){
            update.set(s,entity.get(s));
        }
        mongoTemplate.upsert(query,update,tableName);
    }catch (Exception e){
        e.printStackTrace();
        return 0;
    }
    return 1;
}

你可能感兴趣的:(restTemplate 传递map)