ResTemplate 调用post @RequestBody参数的接口

195 阅读1分钟

被调用服务端接口:

@PostMapping('/test')
public Object test(@RequestBody Map<String, Object> params){
    ...
}

调用方式1:

    public Object getTest(){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE));
        Map<String, Object> param = new HashMap<String, Object>();
        hashMap.put("参数1", "值1");
        hashMap.put("参数2", "值2");
        HttpEntity<Map<String,Object>> httpEntity = new HttpEntity<>(param,httpHeaders);
        Object forObject = restTemplate.postForEntity("/../test",httpEntity,Object.class);
        return forObject;
    }

调用方式2:

    public Object getTest(){        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("参数1", "值1");
        hashMap.put("参数2", "值2");
        Object result = restTemplate.postForObject("/../test", hashMap, Object.class);
        return result;
    }