调用外部接口:
通过RestTemplate调用外部服务
(使用高德地图API实现ip定位及天气查询)
1.导入需要的jar包
可以通过Apache HttpClient官网下载jar包
http://hc.apache.org/httpclient-3.x/
点击download,下载红色的zip
将下载好的jar包复制进web项目的webcontent的lib即可
[ 建议使用maven管理jar包,手动导jar包容易出现版本问题 ]
2.jsp页面
3.控制器controller
@RequestMapping(method = RequestMethod.GET, value = "/ip-to-location")
private String ipToLocation(
@RequestParam(required = false) String ip,
Model model) {
//从页面获取IP,通过service方法,查询位置,在用model将数据显示在页面上
...
return “jsp的名字”;
}
*:注意自动装配的要@Autowired, controller类要@Controller
4.AppConfig ★★
HttpMessageConverter>请求数据转换,将请求转换为高德的API模式,其中>表示任意类型
json支持通过Jackson的jar包,实现MappingJackson2HttpMessageConverter()
@Bean
public RestTemplate restTemplate() {
//使用Apache hc httpclient库来负责底层请求发送
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
RestTemplate rt = new RestTemplate(requestFactory);
List
new MappingJackson2HttpMessageConverter()
);
rt.setMessageConverters(messageConverters);
return rt;
}
5.Service接口
String ipToLocation(String ip);
6.service实现类 ★
@Service
serviceImpl
通过rest模板:
RestTemplate类的.getForObject()将响应转为对象
AmapIpToLocationResponse location = restTemplate.getForObject(url, responseType, uriVariables)
Url:请求的URL
responseType:负责承载数据的类
uriVariables:类似预编译,为防止URL写死,为URL的参数赋值
将高德API获得的响应转为对象,
这个对象是一个响应状态的Java值对象,负责承载所需信息,
将通过高德提供的API获取需要的信息封装进这个Java值对象中
而且,一般情况下,ip应该从environment中拿,
key也可以放入properties中,
甚至可以上升到类的级别,这样就不用每次都从environment中拿啦
ip定位,可查看高德API文档
AmapIpToLocationResponse location = restTemplate.getForObject(
"http://restapi.amap.com/v3/ip?"
+ "ip={ip}&"
+ "key={key}", AmapIpToLocationResponse.class, ip, key);
升级:天气查询
类似IP定位,可查看高德API文档
高德开放平台
高德地图API
http://lbs.amap.com/
一个开放源代码的平台
有很多API提供查看
新手引导完善,获取key,一系列的功能使用说明...
讲解清新,建议使用