一、概述
因要实现不同项目之间的RESTful接口调用,后来发现RestTemplate很好用,这里先简单使用。
二、项目搭建
搭建很简单,可以参考CXF+JAX-RS搭建RESTful风格的WebService。其实不需要这么复杂,不过比较晚了就暂时没写那么细。下面的测试也在此文章中描述的项目基础上进行测试。
三、使用RestTemplate进行调用
先测试一个同一个项目下的调用情况。
import com.alibaba.druid.support.json.JSONUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
/**
* @Author: Qin
* @Description:
* @Date: Created
* @Modified By:
*/
public class RestTemplateTest {
public static void main(String[] args){
// String url = "http://localhost:8085/ciLib/tree.json";
String url = "http://localhost:8080/itil/capabilityWs/getTest";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class);
// System.out.print(responseEntity.toString());
// System.out.println();
System.out.print(JSONUtils.toJSONString(responseEntity.getBody()));
}
}
下面测试不同项目的结果,另一个项目采用的技术基本上是一样的。代码如下,只是把url换成另一个项目中某个具体方法的映射而已,访问controller的某个方法跟前端jsp页面访问controller一样的,返回的数据格式为JSON。
四、RestTemplate说明
RestTemplate很大程度上简化了不同服务间的调用,支持多种不同类型方法(POST/GET等),具体可参考官方说明:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html。下面简单说明RestTemplate常用的方法。需要注意的是,RestTemplate是Spring框架的内容,而RestTemplateBuilder等是SpringBoot框架的内容。
4.1 RestTemplate类
上面的三张截图是TestTemplate类的方法与变量。常用的可能并不多。
getForEntity() 发送get方法的请求,返回ResponseEntity,封装了请求后的响应内容
postForEntity() 发送post方法的请求,返回ResponseEntity,封装了请求后的响应内容
postForObject() 返回对象,postForObject()与postForEntity()有些类似,返回结果不一样
4.2 ResponseEntity
并调用了postForEntity或其它ForEntity的方法后,会返回postForEntity类型,它包含了发送请求后的响应内容,包含状态和拿到的响应数据。
getStatusCode() 请求的状态,对应HttpStatus枚举
getStatusCodeValue() 响应的状态响,对应了HttpStatus枚举的value
getBody() 请求后得到的响应数据,比如发送的查询用户请求,如果成功那得到的就是用户的信息
getHeaders() 请求的头部信息