springboot学习总结(四)RestTemplate用法2

(一)delete请求

delete请求的接口api如下

public void delete(String url, Object... uriVariables) throws RestClientException 
public void delete(String url, Map<String, ?> uriVariables) throws RestClientExceptionpublic void delete(URI url) throws RestClientException 

controller方法

    @DeleteMapping("/deleteEntityTest")
    public JSONObject deleteEntityTest(@RequestParam Long id) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        return jsonObject;
    }

测试方法

    @Test
    public void deleteTest() {
        String url = "http://localhost:8080/deleteEntityTest?id=";
        restTemplate.delete(url, 1);
    }

关于delete和put这两种请求,默认提供的api中返回值都是void,对于这种没法获取返回信息的有时会造成判断的失误。例如,其实请求并未走controller的方法,由于权限等问题被403了,也是正常返回,但是无法判断是否成功delete了。所以直接这样调用不妥。

个人推荐,像delete、put这类请求用他原生的exchange()或者execute()方法

    @Test
    public void deleteTest() {
        String url = "http://localhost:8080/deleteEntityTest?id=1";
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        MimeType mimeType = MimeTypeUtils.parseMimeType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
        // 请求体
        headers.setContentType(mediaType);
        ResponseEntity<JSONObject> entity = restTemplate.exchange(url, HttpMethod.DELETE, new HttpEntity<>(map, headers), JSONObject.class);
        System.out.println("body:" + entity.getBody()
                + ",StatusCode:" + entity.getStatusCode()
                + ",StatusCodeValue:" + entity.getStatusCodeValue()
                + ",:Headers" + entity.getHeaders());
    }

控制台打印信息:

body:{"id":1},StatusCode:200,StatusCodeValue:200,:Headers{Content-Type=[application/json;charset=UTF-8], Transfer-Encoding=[chunked], Date=[Mon, 14 Jan 2019 13:21:54 GMT]}

用这个可以根据返回的状态码,或者返回的信息,来判断是否删除成功。

 

猜你喜欢

转载自www.cnblogs.com/vincentren/p/10269150.html
0条评论
添加一条新回复
  
今日推荐