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请求是非常的方便的。希望大家多多尝试哦。
阅读全文