post请求实践

41 阅读1分钟

 post请求实践

同样的,post请求也有postForObject和postForEntity。

12345public <T> T postForObject(String url, ``@Nullable Object request, Class<T> responseType, Object... uriVariables)``            ``throws RestClientException {}``public <T> T postForObject(String url, ``@Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)``            ``throws RestClientException {}``public <T> T postForObject(URI url, ``@Nullable Object request, Class<T> responseType) ``throws RestClientException {}

  

示例

我用一个验证邮箱的接口来测试。

12345678910111213@Test``public void rtPostObject(){``    ``RestTemplate restTemplate = ``new RestTemplate();``    ``String url = ``"http://47.xxx.xxx.96/register/checkEmail"``;``    ``HttpHeaders headers = ``new HttpHeaders();``    ``headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);``    ``MultiValueMap<String, String> map= ``new LinkedMultiValueMap<>();``    ``map.add(``"email"``, ``"844072586@qq.com"``);     ``HttpEntity<MultiValueMap<String, String>> request = ``new HttpEntity<>(map, headers);``    ``ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.``class );``    ``System.out.println(response.getBody());``}

  

执行结果:

{"status":500,"msg":"该邮箱已被注册","data":null}