RestTemplate讲解三

424 阅读2分钟

RestTemplate提供了GET、POST、PUT、DELETE等丰富的API接口。

  • delete() 在特定的URL上对资源执行HTTP DELETE操作
  • exchange() 在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中映射得到的execute() 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
  • getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
  • getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象
  • postForEntity() POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的
  • postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象
  • headForHeaders() 发送HTTP HEAD请求,返回包含特定资源URL的HTTP头
  • optionsForAllow() 发送HTTP OPTIONS请求,返回对特定URL的Allow头信息
  • postForLocation() POST 数据到一个URL,返回新创建资源的URL
  • put() PUT 资源到特定的URL

一、GET请求

RestTemplate 的get方法有以上几个,可以分为两类: getForEntity和 getForObject

第一种:getForEntity

getForEntity方法的返回值是一个ResponseEntity<T>ResponseEntity<T>是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等

 ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8080/hello", String.class);
    //返回内容
    String body = responseEntity.getBody();
    //状态码
    HttpStatus statusCode = responseEntity.getStatusCode();
    //状态码
    int statusCodeValue = responseEntity.getStatusCodeValue();
    //头部信息
    HttpHeaders headers = responseEntity.getHeaders();

第二种:getForObject

getForObject是对getForEntity的进一步封装,只关注返回的消息体的内容,对其他信息都不关注,此时可以使用getForObject.

String res = restTemplate.getForObject("http://localhost:8080/hello",String.class,headMap,paramMap);

一、POST请求

第一种:postForEntity

postForEntity与getForEntity方法一致

Test test=new Test();
test.setName("hello");
ResponseEntity<Book> responseEntity = restTemplate.postForEntity("http://localhost:8080/test", test, Test.class);
  • 方法的第一参数表示要调用的服务的地址
  • 方法的第二个参数表示上传的参数
  • 方法的第三个参数表示返回的消息体的数据类型

第二种:postForObject

只关注返回的消息体,可以直接使用postForObject。用法和getForObject一致。

第一种:postForLocation

postForLocation也是提交新资源,提交成功之后,返回新资源的URI,postForLocation的参数和前面两种的参数基本一致,只不过该方法的返回值为Uri,这个只需要服务提供者返回一个Uri即可,该Uri表示新资源的位置。

PUT请求

PUT请求可以通过put方法调用,put方法的使用与前面介绍的postForEntity方法的基本一致,只是put方法没有返回值而已。

 Test test = new Test();
 test.setName("红楼梦");
 restTemplate.put("http://localhost:8080/hello/{1}", test, 99);

DELETE请求

在特定的URL上对资源执行HTTP DELETE操作

restTemplate.delete("http://localhost/user/delete/{1}", 100);

删除用户id为100的数据。

delete方法也有几个重载的方法,用法与前面基本一致,不赘述。