在开发中,有的时候我们得调用别人提供的接口API,在这里介绍使用RestTemplate的方式来调用别人的API,简单方便
为了方便将数据转化为json 格式,在这里我引入了fastjson
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.28</version> </dependency>
好了,准备工作做好了,现在就开始吧
附上相关代码
1、先编写RestTemlateConfig,配置好相关信息
/** * Created by hongzhenyue on 18/3/1. */ @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory){ return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ SimpleClientHttpRequestFactory factory=new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(15000); factory.setReadTimeout(5000); return factory; } }
2、然后就可以编写controller了,写了testGetAction 和 testPostAction 这两天API来模拟第三方的API
import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; /** * call API * Created by hongzhenyue on 18/3/1. */ @RestController public class SpringRestTemplateController { @Autowired private RestTemplate restTemplate; /***********HTTP GET method*************/ @GetMapping("/testGetAction") public Object getJson() { JSONObject json = new JSONObject(); json.put("username", "tester"); json.put("pwd", "123456748"); return json; } @GetMapping("/getApi") public String testGet() { String url = "http://localhost:8088/demo/testGetAction"; JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody(); return json.toJSONString(); } /**********HTTP POST method**************/ @PostMapping(value = "/testPostAction") public Object postJson(@RequestBody JSONObject param) { System.out.println(param.toJSONString()); param.put("action", "post"); param.put("username", "tester"); param.put("pwd", "123456748"); return param; } @PostMapping(value = "/postApi") public Object testPost() { String url = "http://localhost:8088/demo/testPostAction"; JSONObject postData = new JSONObject(); postData.put("descp", "request for post"); JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody(); return json.toJSONString(); } }
然后在postman上调用getApi,然后查看结果
{"pwd":"123456748","username":"tester"}
在postman上post 请求 postApi,查看结果
{"action":"post","pwd":"123456748","descp":"request for post","username":"tester"}
由此可见,我们已经成功得调用到了其他的API
版权声明:本文为qq_15452971原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。