Spring boot resttemplate 其实也可以当成http client来用

来源:互联网 发布:js 数组 contains方法 编辑:程序博客网 时间:2024/06/18 09:37

这段时间都在用Spring boot,真的是非常的方便,去除了繁琐的copy文件搭建项目的问题。

在这期间遇到了一个要请求别人服务器接口的问题,一开始是用到了http client来请求的,但是个人觉得挺麻烦。于是乎就尝试了下请求服务提供者的用到的restTemplate了。想不到也是可以请求成功的,当中的原理本人还是暂时不知道的啦。哈哈

废话不多说 贴上样例代码:

GET请求例子:
我们假设请求一个获取ip地址是那个地区的接口:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=218.4.255.255

public static void main(String[] args) {        RestTemplate restTemplate = new RestTemplate();        String jsonStr = restTemplate.getForEntity("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format={0}&ip={1}", String.class, "json", "218.4.255.255").getBody();        System.out.println(jsonStr);    }

看吧 简简单单的一个get请求就这么完成了,都没有引入其他工具包。

POST请求例子:
post请求可能就有一点而麻烦了,假设请求一个表单,有name和age参数

public static void main(String[] args) throws JsonProcessingException {        RestTemplate restTemplate = new RestTemplate();        HttpHeaders headers = new HttpHeaders();        //请求头设置                  headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);        ObjectMapper mapper = new ObjectMapper();        Map<String, String> params= Maps.newHashMap();        params.put("name", "小周");        params.put("age", "18");        String value = mapper.writeValueAsString(params);        HttpEntity<String> requestEntity = new HttpEntity<String>(value, headers);        //  执行HTTP请求        ResponseEntity<String> response = restTemplate.postForEntity("post_url", requestEntity , String.class );        System.out.println(response.getBody());    }

其实用restTemplate请求是非常的方便的。希望大家多多尝试哦。

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 四川省平昌县 平南北帝山景区 黎平景区 连平景区 平塘天眼景区攻略 平望房子 平望镇 末端爱情 惠若琪洞松 东莞中惠松湖城 平板仪 平板在线 平板的用处 平板的作用 平板有啥用 什么平板好 平板选择 好用的平板 android平板电脑 平板电脑可以 掌上电脑和平板电脑的区别 平板电脑能干嘛 双系统平板电脑推荐 平板电脑的功能和用处 平板电脑用途 平板电脑有什么用途 平板电脑的作用 平板电脑有什么用 什么平板电脑性价比高 平板电脑有什么用处 平板电脑吧 笔记本吧 ipad怎么用 ipad使用教程 平板振动夯 平板震动夯 平板夯 进口平板夯 平板夯图片 平板式太阳能热水器 平板式扫描仪