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上的分数都很高,建议使用。
阅读全文
0 0
- Spring之RestTemplate介绍
- spring 之 RestTemplate 用法
- spring RestTemplate
- spring restTemplate
- Spring RestTemplate
- REST In Spring : RestTemplate
- Spring RestTemplate Json 例子
- spring RestTemplate用法详解
- Spring restTemplate 超时配置
- spring的RestTemplate
- spring RestTemplate用法详解
- 使用Spring RestTemplate测试
- Spring RestTemplate 实践
- spring RestTemplate用法详解
- Spring RestTemplate详解
- spring RestTemplate用法详解
- spring RestTemplate用法详解
- Spring RestTemplate工具类
- jsp页面输出HTML产生多余空格(out.print())的解决办法
- python 爬取 某平台 LOL主播姓名+加人气,然后进行排序
- 在字符串中删除指定字符
- CPU100%问题定位
- CMake 链接第三方的库 和 添加C++11的支持
- Spring之RestTemplate介绍
- Axure授权注册码
- Javascript异步编程
- javax.el.ExpressionFactory.newInstance()Ljavax/el/ExpressionFactory;错误
- linux sed
- 一些统计量
- radio和checkbox例子
- #define用法【转】
- 传智播客郑州校区PHP就业9期开班典礼