Spring之RestTemplate介绍

来源:互联网 发布:ubuntu imatch 编辑:程序博客网 时间:2024/06/18 13:13

RestTemplate设计是为了Spring更好的请求并解析Restful风格的接口返回值而设计的,通过这个类可以在请求接口时直接解析对应的类。
在前一篇文章《搭建简单的Restful风格的web服务》的基础上,我们写一个client调用一下http://localhost:8080/hello这个接口,返回为我们自定义的ResultBean。
先重写一下ResultBean的toString方法,方便我们打印返回值。

    @Override    public String toString(){        StringBuilder builder = new StringBuilder();        builder.append("code: ");        if( code == SUCCESS){            builder.append("SUCCESS, ");            if(null != data) {                builder.append("data: ");                builder.append(data.toString());            }        }else {            builder.append("FAIL, ");            builder.append(errorMsg);        }        return builder.toString();    }

写一个Client:

public class Client {    public static void main(String[] args) {        RestTemplate restTemplate = new RestTemplate();        ResultBean bean =  restTemplate.getForObject("http://localhost:8080/hello?name=CYF", ResultBean.class);        System.out.println(bean.toString());    }}

启动我们的服务,然后执行我们的这个Client的main方法,控制台可以看到打印结果。

16:51:23.169 [main] DEBUG o.s.web.client.RestTemplate - Created GET request for "http://localhost:8080/hello?name=CYF"16:51:23.273 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [application/json, application/*+json]16:51:23.311 [main] DEBUG o.s.web.client.RestTemplate - GET request for "http://localhost:8080/hello?name=CYF" resulted in 200 (OK)16:51:23.312 [main] DEBUG o.s.web.client.RestTemplate - Reading [class hello.ResultBean] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@65987993]code: SUCCESS, data: hello CYF

更多RestTemplate的使用可以见其API。

不过有两个开源项目okhttp和fastjson一起使用也能做到这个效果,这两个包在github上的分数都很高,建议使用。