springboot集成restTemplate接口调用(13)

x33g5p2x  于2021-08-23 转载在 Spring  
字(5.7k)|赞(0)|评价(0)|浏览(428)

一restTemplate简介

restTemplate底层是基于HttpURLConnection实现的restful风格的接口调用,类似于webservice,rpc远程调用,但其工作模式更加轻量级,方便于rest请求之间的调用,完成数据之间的交互,在springCloud之中也有一席之地。大致调用过程如下图,如果想学习其底层具体如何实现可以查看我的文章 restTemplate源码详解深入剖析底层实现思路
在这里插入图片描述

二restTemplate常用方法列表

forObeject跟forEntity有什么区别呢?主要的区别是forEntity的功能更加强大一些,其返回值是一个ResponseEntity<T>,更加方便我们获得响应的body,head等信息。exchange方法和其他方法不同之处就是能自己定义的rest请求方式。

2.1 get请求方法预览

在这里插入图片描述

2.2 post方法请求预览

在这里插入图片描述

2.3put请求方法预览

在这里插入图片描述

2.4 delete请求方法预览

在这里插入图片描述

2.5exchange方法预览

在这里插入图片描述

三rest接口调用示例

restTemplate配置
首先本次示例采用的是springboot2.x以上版本,javaSE8;其次发布的服务端是同一台机子,服务端端口8090,客户端端口8080;类路径youku1327;在实际工作中最常用是get,post请求方式;restTemplate简单配置如下:

/**
 * @Author lsc
 * @Description <p> </p>
 * @Date 2019/10/14 11:40
 * @Version 1.0
 */
@Configuration
public class RestTemplateConfig {

    // 配置 RestTemplate
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        // 创建一个 httpCilent 简单工厂
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 设置连接超时
        factory.setConnectTimeout(15000);
        // 设置读取超时
        factory.setReadTimeout(5000);
        return factory;
    }
}

3.1 get请求接口调用示例

服务费发布的端口

    @GetMapping("user")
    public String getUser(){
        return "youku1327";
    }

    @GetMapping("user/{name}")
    public String getUserName(@PathVariable String name){
        return name;
    }

客户端调用
GET参数说明:

  • 第一个参数是url。
  • 第二个参数是返回值类型。
  • 第三个参数是uri地址路径变量。
 /*
     * @Author lsc
     * @Description  <p> 获得无参的get请求 </p>
     * @Date 2019/10/17 21:15
     * @Param []
     * @return void
     **/
    @Test
    public void testGETNoParams(){
        String result = restTemplate.getForObject("http://localhost:8090/youku1327/user", String.class);
        System.out.println(result);
    }
    /*
     * @Author lsc
     * @Description  <p> URL带参 </p>
     * @Date 2019/10/18 13:49
     * @Param []
     * @return void
     **/
    @Test
    public void testGETParams(){
        // http://localhost:8090/youku1327/user/{1}
        String result = restTemplate.getForObject("http://localhost:8090/youku1327/user/{name}", String.class,"lsc");
        System.out.println(result);
    }

3.2 post请求示例

POST请求参数说明

  • 第一个参数是url。
  • 第二个参数是请求参数。
  • 第三个参数是返回值类型。
  • 第三个参数是uri地址路径变量。

服务端发布接口

 @PostMapping("provider")
    public ResponseEntity<String> addData(@RequestBody JSONObject jsonObject){
        String user = (String) jsonObject.get("user");
        return ResponseEntity.ok(user);
    }

客户端接口调用

 /*
     * @Author lsc
     * @Description  <p> post</p>
     * @Date 2019/10/18 23:23
     * @Param []
     * @return void
     **/
    @Test
    public void testPostMethod() throws MalformedURLException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user","youku1327");
        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<JSONObject> httpEntity = new HttpEntity(jsonObject,httpHeaders);
        String url = "http://localhost:8090/youku1327/provider";
        ResponseEntity<String> mapResponseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        System.out.println(mapResponseEntity.getBody());
    }

3.3 put接口调用示例

PUT请求参数说明

  • 第一个参数是url。
  • 第二个参数是请求参数。
  • 第三个参数是uri地址路径变量。

服务端发布接口

 @PutMapping("provider/{id}")
    public ResponseEntity<JSONObject> updateData(@PathVariable Long id, @RequestBody JSONObject jsonObject){
        Object object = jsonObject.get("user");
        jsonObject.put("id",id);
        // {"id":1327,"user":"youku1327"}
        System.out.println(jsonObject);
        return ResponseEntity.ok(jsonObject);
    }

客户端接口调用

    /*
     * @Author lsc
     * @Description  <p> put</p>
     * @Date 2019/10/18 23:23
     * @Param
     * @return
     **/

    @Test
    public void testPutMethod() throws MalformedURLException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user","youku1327");
        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<JSONObject> httpEntity = new HttpEntity(jsonObject,httpHeaders);
        String url = "http://localhost:8090/youku1327/provider/{id}";
        restTemplate.put(url, httpEntity, 1327);
    }

3.4delete请求示例

DELETE请求参数说明

  • 第一个参数是url
  • 第二个参数uri地址路径变量。

服务端发布接口

    @DeleteMapping("provider/{id}")
    public ResponseEntity<String> delData(@PathVariable Long id){
        String result = "delete"+id+"success";
        // delete1327success
        System.out.println(result);
        return ResponseEntity.ok(result);
    }

客户端调用接口

  /*
     * @Author lsc
     * @Description  <p> delete</p>
     * @Date 2019/10/18 23:22
     * @Param []
     * @return void
     **/
    @Test
    public void testDelete(){
        String url = "http://localhost:8090/youku1327/provider/{id}";
        restTemplate.delete(url,1327);
    }

3.5 exchange

参数说明:

  • 第一个参数是url。
  • 第二个参数是请求方式。
  • 第三个参数是请求实体。
  • 第四个参数是返回值类型。
  • 第五个参数是uri地址变量。

服务端发布接口

    @GetMapping("user/{name}")
    public String getUserName(@PathVariable String name){
        return name;
    }

客户端调用接口

    /*
     * @Author lsc
     * @Description  <p> exchange</p>
     * @Date 2019/10/18 23:22
     * @Param []
     * @return void
     **/
    @Test
    public void testExchange(){
        String url = "http://localhost:8090/youku1327/user/{name}";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity httpEntity = new HttpEntity(httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, "youku1327");
        System.out.println(exchange.getBody());
    }

3.6 设置cookie请求示例

	// 获取cookie
	String cookieUrl= "";
        List<String> cookies =new ArrayList<String>();
        JSONArray jsonArray = restTemplate.getForObject(cookieUrl, JSONArray.class);
        String jsession = jsonArray.getJSONObject(0).getString("jsession");
        String cookie = "JSESSIONID="+jsession+"; Path=/; HttpOnly;";
        cookies.add(cookie);
	// 请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        httpHeaders.add(HttpHeaders.COOKIE,cookie);
        HttpEntity httpEntity = new HttpEntity(null, httpHeaders);
        // 请求地址
        String url = "";
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, JSONObject.class);

相关文章