SpringBoot的Http请求

it2023-01-23  52

RestTemplate中,对POST请求可以通过三个方法调用实现

一 postForEntity函数

postForEntity(String url,Object request,Class responseType,Object ... urlVariables) postForEntity(String url,Object request,Class responseType,Map urlVariables) postForEntity(String url,Object request,Class responseType)

二 postForObject函数

postForObject(String url,Object request,Class responseType,Object ... urlVariables) postForObject(String url,Object request,Class responseType,Map urlVariables) postForObject(String url,Object request,Class responseType)

三 postForLocation函数

postForLocation(String url,Object request,Object ... urlVariables) postForLocation(String url,Object request,Map urlVariables) postForLocation(String url,Object request)

四 实例

1.创建RestTemplate @Autowired private RestTemplate restTemplate; 2.创建请求头 HttpHeaders headers = new HttpHeaders(); 3.设置请求头传送信息编码格式 MediaType type = MediaType.APPLICATION_JSON_UTF8; headers.setContentType(type); 4.创建需要传输的数据 Map<String, Object> map = new HashMap<String,object>(); 5.创建请求信息传输对象 org.springframework.http.HttpEntity<Object> request = new org.springframework.http.HttpEntity<Object>(map, headers); 6.传输数据,并获取返回数据 ResponseEntity<Object> entity = restTemplate.postForEntity(url, request, Object.class); 7.获取返回的对象 Object object = entity.getBody();
最新回复(0)