赞
踩
一般我们的Spring Boot工程都是被请求的一方,但某些情况下我们也需要调用别人的接口以实现逻辑,传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐,而Spring提供了一种简单便捷的模板类来进行操作,这就是RestTemplate。
RestTemplate是Spring用于同步client端的核心类,简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果。默认情况下,RestTemplate默认依赖jdk的HTTP连接工具。当然你也可以 通过setRequestFactory属性切换到不同的HTTP源,比如Apache HttpComponents、Netty和OkHttp。
Spring启动器中内置了RestTemplate,无需引入其他依赖,只需要spring-boot-starter-web即可。
<!--spring boot启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@Configuration public class ResTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) { return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); //超时设置 factory.setReadTimeout(5000);//ms factory.setConnectTimeout(15000);//ms return factory; } }
将RestTemplate对象注入
@RunWith(SpringRunner.class)
@SpringBootTest
public class RestTemplateTest {
@Autowired
private RestTemplate restTemplate;
}
@Test public void RestTemplateTestGet() { /** * getForObject * 参数1 要请求的地址的url 必填项 * 参数2 响应数据的类型 是String 还是 Map等 必填项 * 参数3 请求携带参数 选填 * getForObject 方法的返回值就是 被调用接口响应的数据 */ String url = "http://localhost:5000/users/1"; //1. getForObject() //先获取返回的字符串,若想获取属性,可以使用gson转化为实体后get方法获取 String result = restTemplate.getForObject(url, String.class); System.out.println(result);//{"code":"0","data":{"address":"北京市海淀区","id":1,"password":"123456","role":0,"sex":0,"telephone":"10086","username":"小明"},"msg":"操作成功"} //2. getForEntity() //获取实体ResponseEntity,可以用get函数获取相关信息 ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); System.out.println("responseEntity.getStatusCode() = " + responseEntity.getStatusCode()); System.out.println("responseEntity.getStatusCodeValue() = " + responseEntity.getStatusCodeValue()); //responseEntity.getStatusCodeValue() = 200 System.out.println("responseEntity.getBody() = " + responseEntity.getBody()); //responseEntity.getBody() = {"code":"0","data":{"address":"北京市海淀区","id":1,"password":"123456","role":0,"sex":0,"telephone":"10086","username":"小明"},"msg":"操作成功"} System.out.println("responseEntity.getHeaders() = " + responseEntity.getHeaders());//responseEntity.getHeaders() = [Content-Type:"application/json", Content-Length:"158", Server:"Werkzeug/0.14.1 Python/3.7.0", Date:"Sat, 16 Oct 2021 06:01:26 GMT"] System.out.println("responseEntity.getClass() = " + responseEntity.getClass());//responseEntity.getClass() = class org.springframework.http.ResponseEntity }
@Test public void RestTemplateTestPost() { //String url = "http://127.0.0.1:5000/register"; String url = "http://127.0.0.1:5000/login"; //LinkedMultiValueMap一个键对应多个值,对应format-data的传入类型 LinkedMultiValueMap<String, String> request = new LinkedMultiValueMap<>(); //入参 request.set("username","baihui"); request.set("password", "123456"); request.set("sex", "0"); request.set("telephone", "13172724946"); //请求 String result = restTemplate.postForObject(url,request,String.class); System.out.println(result); ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class); System.out.println("responseEntity.getBody() = " + responseEntity.getBody()); }
@Test public void RestTemplateTestUpload() throws IOException { String httpMethod = "http://127.0.0.1:5555/photo"; String args = "可以添加其他属性参数"; MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>(); paramMap.add("args", args); //打开图片并写入流 File file=new File("D:\\WorkProject\\static\\output\\04.png"); byte[] bytesArray = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(bytesArray); //read file into bytes[] fis.close(); ByteArrayResource contentsAsResource = new ByteArrayResource(bytesArray) { //重载设置文件名 @Override public String getFilename() { return "04.png"; } }; paramMap.add("file", contentsAsResource); String result = restTemplate.postForObject(httpMethod,paramMap,String.class); System.out.println("result = " + result); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。