Java中使用RestTemplate调用api

java中可以使用3种方式调用api

  • HttpURLConnection
  • HttpClient
  • RestTemplate

这里要讲的是RestTemplate的方式。

REST的基础知识

当谈论REST时,有一种常见的错误就是将其视为“基于URL的Web服务”——将REST作为另一
种类型的远程过程调用(remote procedure call,RPC)机制,就像SOAP一样,只不过是通过简单
的HTTP URL来触发,而不是使用SOAP大量的XML命名空间

恰好相反,REST与RPC几乎没有任何关系RPC是面向服务的,并关注于行为和动作而REST
是面向资源的,强调描述应用程序的事物和名词。

更简洁地讲,REST就是将资源的状态以最适合客户端或服务端的形式从服务器端转移到客户
端(或者反过来)。

在REST中,资源通过URL进行识别和定位。至于RESTful URL的结构并没有严格的规则,但是
URL应该能够识别资源,而不是简单的发一条命令到服务器上。再次强调,关注的核心是事
物,而不是行为.,

Spring 中如何使用Rest资源

借助 RestTemplate,Spring应用能够方便地使用REST资源
Spring的 RestTemplate访问使用了模版方法的设计模式.

模版方法将过程中与特定实现相关的部分委托给接口,而这个接口的不同实现定义了接口的不同行为.

RestTemplate定义了36个与REST资源交互的方法,其中的大多数都对应于HTTP的方法。
其实,这里面只有11个独立的方法,其中有十个有三种重载形式,而第十一个则重载了六次,这样一共形成了36个方法。

  • 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

实际上,由于Post 操作的非幂等性,它几乎可以代替其他的CRUD操作.

Get请求

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

首先看 getForEntity() 的返回值类型 ResponseEntity

<T> ResponseEntity<T> getForEntity()

它继承了HttpEntity. 封装了返回的响应信息,包括 响应状态,响应头 和 响应体.

测试: getForEntity

  1. 无参数的 getForEntity 方法
 @RequestMapping("getForEntity")
    public List<UserEntity> getAll2() {
        ResponseEntity<List> responseEntity = restTemplate.getForEntity("http://localhost/getAll", List.class);
        HttpHeaders headers = responseEntity.getHeaders();
        HttpStatus statusCode = responseEntity.getStatusCode();
        int code = statusCode.value();

        List<UserEntity> list = responseEntity.getBody();

        System.out.println(list.toString());
        return list;

    }

  2.有参数的 getForEntity 请求,参数列表,可以使用 {} 进行url路径占位符

//有参数的 getForEntity 请求,参数列表
    @RequestMapping("getForEntity/{id}")
    public UserEntity getById2(@PathVariable(name = "id") String id) {

        ResponseEntity<UserEntity> responseEntity = restTemplate.getForEntity("http://localhost/get/{id}", UserEntity.class, id);
        UserEntity userEntity = responseEntity.getBody();
        return userEntity;
    }

  3.有参数的 get 请求,使用map封装参数

    //有参数的 get 请求,使用map封装参数
    @RequestMapping("getForEntity/{id}")
    public UserEntity getById4(@PathVariable(name = "id") String id) {
        HashMap<String, String> map = new HashMap<>();
        map.put("id",id);

        ResponseEntity<UserEntity> responseEntity = restTemplate.getForEntity("http://localhost/get/{id}", UserEntity.class, map);
        UserEntity userEntity = responseEntity.getBody();

        return userEntity;
    }

这里也可以用JSONObject。

而对于上传文件时,可以使用

MultiValueMap<String, Object> resultMap = new LinkedMultiValueMap<>();
    Resource resource = new FileSystemResource(file);
    param.put("file", resource);

参考网址:

https://blog.csdn.net/itguangit/article/details/78825505

上传文件

https://blog.csdn.net/weixin_30539625/article/details/102054205

原文地址:https://www.cnblogs.com/Vincent-yuan/p/14860989.html