概述
因要实现不同项目之间的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。