认识微服务-Http客户端工具
3.Http客户端工具
既然微服务选择了Http,那么我们就需要考虑自己来实现对请求和响应的处理。不过开源世界已经有很多的http客户端工具,能够帮助我们做这些事情,例如:
- HttpClient
- OKHttp
- URLConnection
接下来,我们就一起了解一款比较流行的客户端工具:HttpClient
3.1.HttpClient
3.1.1.介绍
HttpClient是Apache公司的产品,是Http Components下的一个组件。
官网地址:http://hc.apache.org/index.html
特点:
- 基于标准、纯净的Java语言。实现了Http1.0和Http1.1
- 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)
- 支持HTTPS协议。
- 通过Http代理建立透明的连接。
- 自动处理Set-Cookie中的Cookie。
3.1.2.使用
我们导入课前资料提供的demo工程:《http-demo》
发起get请求:
@Test public void testGet() throws IOException { HttpGet request = new HttpGet("http://www.baidu.com"); String response = this.httpClient.execute(request, new BasicResponseHandler()); System.out.println(response); }
发起Post请求:
@Test public void testPost() throws IOException { HttpPost request = new HttpPost("http://www.oschina.net/"); request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); String response = this.httpClient.execute(request, new BasicResponseHandler()); System.out.println(response); }
尝试访问昨天编写的接口:http://localhost/hello
这个接口返回一个User对象
@Test public void testGetPojo() throws IOException { HttpGet request = new HttpGet("http://localhost/hello"); String response = this.httpClient.execute(request, new BasicResponseHandler()); System.out.println(response); }
我们实际得到的是一个json字符串:
{ "id": 8, "userName": "liuyan", "password": "123456", "name": "柳岩", "age": 21, "sex": 2, "birthday": "1995-08-07T16:00:00.000+0000", "created": "2014-09-20T03:41:15.000+0000", "updated": "2014-09-20T03:41:15.000+0000", "note": "柳岩同学在传智播客学表演" }
如果想要得到对象,我们还需要手动进行Json反序列化,这一点比较麻烦。
3.1.3.Json转换工具
HttpClient请求数据后是json字符串,需要我们自己把Json字符串反序列化为对象,我们会使用JacksonJson工具来实现。
JacksonJson
是SpringMVC内置的json处理工具,其中有一个ObjectMapper
类,可以方便的实现对json的处理:
对象转json
// json处理工具 private ObjectMapper mapper = new ObjectMapper(); @Test public void testJson() throws JsonProcessingException { User user = new User(); user.setId(8L); user.setAge(21); user.setName("柳岩"); user.setUserName("liuyan"); // 序列化 String json = mapper.writeValueAsString(user); System.out.println("json = " + json); }
结果:
json转普通对象
// json处理工具 private ObjectMapper mapper = new ObjectMapper(); @Test public void testJson() throws IOException { User user = new User(); user.setId(8L); user.setAge(21); user.setName("柳岩"); user.setUserName("liuyan"); // 序列化 String json = mapper.writeValueAsString(user); // 反序列化,接收两个参数:json数据,反序列化的目标类字节码 User result = mapper.readValue(json, User.class); System.out.println("result = " + result); }
结果:
json转集合
json转集合比较麻烦,因为你无法同时把集合的class和元素的class同时传递到一个参数。
因此Jackson做了一个类型工厂,用来解决这个问题:
// json处理工具 private ObjectMapper mapper = new ObjectMapper(); @Test public void testJson() throws IOException { User user = new User(); user.setId(8L); user.setAge(21); user.setName("柳岩"); user.setUserName("liuyan"); // 序列化,得到对象集合的json字符串 String json = mapper.writeValueAsString(Arrays.asList(user, user)); // 反序列化,接收两个参数:json数据,反序列化的目标类字节码 List<User> users = mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, User.class)); for (User u : users) { System.out.println("u = " + u); } }
结果:
json转任意复杂类型
当对象泛型关系复杂时,类型工厂也不好使了。这个时候Jackson提供了TypeReference来接收类型泛型,然后底层通过反射来获取泛型上的具体类型。实现数据转换。
// json处理工具 private ObjectMapper mapper = new ObjectMapper(); @Test public void testJson() throws IOException { User user = new User(); user.setId(8L); user.setAge(21); user.setName("柳岩"); user.setUserName("liuyan"); // 序列化,得到对象集合的json字符串 String json = mapper.writeValueAsString(Arrays.asList(user, user)); // 反序列化,接收两个参数:json数据,反序列化的目标类字节码 List<User> users = mapper.readValue(json, new TypeReference<List<User>>(){}); for (User u : users) { System.out.println("u = " + u); } }
结果:
3.3.Spring的RestTemplate
Spring提供了一个RestTemplate模板工具类,对基于Http的客户端进行了封装,并且实现了对象与json的序列化和反序列化,非常方便。RestTemplate并没有限定Http的客户端类型,而是进行了抽象,目前常用的3种都有支持:
- HttpClient
- 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/hello", User.class); System.out.println(user); } }
- 通过RestTemplate的getForObject()方法,传递url地址及实体类的字节码,RestTemplate会自动发起请求,接收响应,并且帮我们对响应结果进行反序列化。
学习完了Http客户端工具,接下来就可以正式学习微服务了。