2.get请求实践
2.1.getForObject()方法
| 123 | public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables){}``public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables)``public <T> T getForObject(URI url, Class<T> responseType) |
|---|
getForObject()其实比getForEntity()多包含了将HTTP转成POJO的功能,但是getForObject没有处理response的能力。因为它拿到手的就是成型的pojo。省略了很多response的信息。
2.1.1 POJO:
| 12345678910111213 | public class Notice {`` ``private int status;`` ``private Object msg;`` ``private List<DataBean> data;``}``public class DataBean {`` ``private int noticeId;`` ``private String noticeTitle;`` ``private Object noticeImg;`` ``private long noticeCreateTime;`` ``private long noticeUpdateTime;`` ``private String noticeContent;``} |
|---|
示例:2.1.2 不带参的get请求
| 12345678910 | /**`` ``* 不带参的get请求`` ``*/`` ``@Test`` ``public void restTemplateGetTest(){`` ``RestTemplate restTemplate = ``new RestTemplate();`` ``Notice notice = restTemplate.getForObject(``"http://xxx.top/notice/list/1/5"`` ``, Notice.``class``);`` ``System.out.println(notice);`` ``} |
|---|
控制台打印:
| 1234567 | INFO ``19076 --- [ main] c.w.s.c.w.c.HelloControllerTest ``: Started HelloControllerTest in ``5.532 seconds (JVM running ``for 7.233``) Notice{status=``200``, msg=``null``, data=[DataBean{noticeId=``21``, noticeTitle=``'aaa'``, noticeImg=``null``,``noticeCreateTime=``1525292723000``, noticeUpdateTime=``1525292723000``, noticeContent=``'<p>aaa</p>'``},``DataBean{noticeId=``20``, noticeTitle=``'ahaha'``, noticeImg=``null``, noticeCreateTime=``1525291492000``,``noticeUpdateTime=``1525291492000``, noticeContent=``'<p>ah.......' |
|---|
示例:2.1.3 带参数的get请求1
Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/{1}/{2}"
, Notice.class,1,5);
明眼人一眼能看出是用了占位符{1}。
示例:2.1.4 带参数的get请求2
| 12345 | Map<String,String> map = ``new HashMap();`` ``map.put(``"start"``,``"1"``);`` ``map.put(``"page"``,``"5"``);`` ``Notice notice = restTemplate.getForObject(``"http://fantj.top/notice/list/"`` ``, Notice.``class``,map); |
|---|
明眼人一看就是利用map装载参数,不过它默认解析的是PathVariable的url形式。