通过RestTemplate调用外部服务

来源:互联网 发布:电脑游戏截图软件 编辑:程序博客网 时间:2024/06/04 00:22

调用外部接口:

通过RestTemplate调用外部服务

(使用高德地图API实现ip定位及天气查询)

 

1.导入需要的jar


可以通过Apache HttpClient官网下载jar

http://hc.apache.org/httpclient-3.x/

点击download,下载红色的zip

 

将下载好的jar包复制进web项目的webcontentlib即可

[ 建议使用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支持通过Jacksonjar包,实现MappingJackson2HttpMessageConverter()

 

@Bean

public RestTemplate restTemplate() {

//使用Apache hc httpclient库来负责底层请求发送

ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

RestTemplate rt = new RestTemplate(requestFactory);

List<HttpMessageConverter<?>> messageConverters = Arrays.asList(

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,一系列的功能使用说明...

讲解清新,建议使用

原创粉丝点击