一、restTemplate的使用
我们直接通过实例来说明和理解。
首先新建一个子模块,用来测试restTemplate的使用
在测试的主类中添加如下代码,我们就能够获取百度界面的html文件。
代码如下:
package com.example.resttemplate01; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.web.client.RestTemplate; @SpringBootTest class RestTemplate01ApplicationTests { @Test void contextLoads() { //在java中发送http请求 RestTemplate restTemplate = new RestTemplate(); //这个对象有get、post、put、delete方法,可以返回一个实体或者对象 String url = "https://www.baidu.com"; String result = restTemplate.getForObject(url,String.class); System.out.println(result); } }
执行结果如下:
然后我们尝试访问自己写的接口,在这个项目中新建一个controller,编写一个接口进行测试。
首先我们测试get类型的请求,get类型不需要传递太多的参数。
在测试的主类中新增加一个测试get接口的方法,代码如下:
我们先把整个项目启动起来,这样才能访问到接口,然后运行这个测试方法,会发现相应内容都会成功打印。
接下来我们测试post类型的请求,post类型有两种传参方式,一种是json格式数据,实参需要用json注解来接收,另外一种是表单的形式,可以直接使用实体类型来接收。
首先我们新增一个User的实体类:
我们在新增测试接口。
注意两种接收方式的请求头不一样,json格式的请求头为:
而表单形式的请求头为:
最后我们在测试主类中用restTemplate来访问这几个接口。
以json形式访问代码如下:
@Test void testPost1() { RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/testpost1"; User user = new User("zhangsan",15,10000D); //这里之所以可以直接传对象,是因为对象在web中传输时会被自动转成json格式 String result = restTemplate.postForObject(url,user,String.class); System.out.println(result); }
以表单形式访问代码如下:
@Test void testPost2() { RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/testpost2"; //传递表单参数 LinkedMultiValueMap<String,Object> map = new LinkedMultiValueMap<>(); map.add("name","lisi"); map.add("age",15); map.add("salary",15859D); String result = restTemplate.postForObject(url,map,String.class); System.out.println(result); }
都可以实现http的通信。
二、Ribbon
标签:restTemplate,url,SpringCloud,RestTemplate,笔记,result,测试,Ribbon,String From: https://www.cnblogs.com/worthmove/p/16797406.html