Spring提供了一个RestTemplate模板工具类,对基于Http的客户端进行了封装,并且实现了对象与json的序列化和反序列化,非常方便。RestTemplate并没有限定Http的客户端类型,而是进行了抽象,目前常用的3种都有支持:
OkHttp
JDK原生的URLConnection(默认的)
首先在项目中注册一个RestTemplate
对象,可以在启动类位置注册:
- @SpringBootApplication
- public class HttpDemoApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(HttpDemoApplication.class, args);
- }
-
- @Bean
- public RestTemplate restTemplate() {
- // 默认的RestTemplate,底层是走JDK的URLConnection方式。
- return new RestTemplate();
- }
- }
在测试类中直接@Autowired
注入:
返回对象时的用法:
- @RunWith(SpringRunner.class)
- @SpringBootTest(classes = HttpDemoApplication.class)
- public class HttpDemoApplicationTests {
-
- @Autowired
- private RestTemplate restTemplate;
-
- @Test
- public void httpGet() {
- User user = this.restTemplate.getForObject("http://localhost:8080/hello", User.class); //返回对象时的用法
-
- System.out.println(user);
- }
- }
返回集合时的用法:
- package com.leyou.httpdemo;
- import com.leyou.httpdemo.pojo.Users;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringRunner;
- import org.springframework.web.client.RestTemplate;
-
- import java.util.Arrays;
- import java.util.List;
-
- @RunWith(SpringRunner.class)
- @SpringBootTest(classes = HttpDemoApplication.class)
- public class HttpDemoApplicationTests {
-
- @Autowired
- private RestTemplate restTemplate;
-
- @Test
- public void httpGet() {
-
- Users[] users = restTemplate.getForObject("http://localhost:9090/user", Users[].class);
- List
usersList = Arrays.asList(users); - System.out.println("====================================================================");
- //foreach语句遍历
- for (Users user:usersList) {
- System.out.println(user);
- }
- System.out.println("====================================================================");
-
- }
-
- }
通过RestTemplate的getForObject()方法,传递url地址及实体类的字节码,RestTemplate会自动发起请求,接收响应,并且帮我们对响应结果进行反序列化。