Spring本身提供了访问RESTFul服务的的工具RestTemplate,在Spring Android项目中也提供了该工具。正如其名所示,其概念上和JdbcTemplate, JmsTemplate类似,虽然RestTemplate看似主要在于和遵循RESTful架构的服务交互,但是其实RestTemplate可以作为一个通用的http访问工具使用。
RestTemplate 的底层默认使用java.net实现http处理,但是通过指定ClientHttpRequestFactory的不同实现其也可以配置为使用 apache httpclient,HttpComponentsClientHttpRequestFactory作为ClientHttpRequestFactory的实现则会用httpclient创建请求。
RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
RestTemplate 针对常用的六种http方法提供了相应的实现,每种方法都有三种重载,两个以String方式接受请求地址的,该地址将在内部被编码一次,所以传入的地址需要是没被编码的,地址可以包括模板变量,这两个方法的模板变量一个以Map<String, String>输入,一个以可变String参数输入。
String result = restTemplate.getForObject(
"http://example.com/hotels/{hotel}/bookings/{booking}", String.class,"42", "21");
Map<String, String> vars = Collections.singletonMap("hotel", "42");
String result = restTemplate.getForObject(
"http://example.com/hotels/{hotel}/rooms/{hotel}"