Spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。
RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过setRequestFactory方法替换为例如 Apache HttpComponents、Netty或OkHttp等其它HTTP library。
直接上代码了
1.我们先定义一个对象来接收返回的数据。(我这里的例子调用的是谷歌地图的API,正常来说我们的对象应该定义为泛型)
@Data
public class TestObject {
private int status;
private String message;
private List<Map<String,Object>> result;
}
2.具体调用代码。(我这里采用的是多线程的方式,防止数据太多的时候跑的时间过长)
public class TestThread implements Callable<TestObject> {
//你申请的apk
private final static String apk = "*******************";
List<String> query;
String region;
/**
* 总之这些就是第三方接口的参数啦!
* @param query 查询的关键字
* @param region 查询的地区
*/
public TestThread(List<String> query,String region) {
this.query = query;
this.region = region;
}
@Override
public TestObject call() throws Exception {
StringBuilder sb = new StringBuilder();
for (String s:query) {
sb = sb.append(s);
}
RestTemplate restTemplate = new RestTemplate();
String url = "http://api.map.baidu.com/place/v2/suggestion?query=" + sb
+ "®ion=" + region
+ "&city_limit=true&output=json&ak=" + apk;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<String> entity = new HttpEntity<String>(headers);
//看得懂吧
String strbody = restTemplate.exchange(url, HttpMethod.GET, entity,String.class).getBody();
TestObject object = JSONObject.parseObject(strbody, TestObject.class);
return object;
}
}
3.接下来就是调用啦
public static void main(String[] args) throws InterruptedException, ExecutionException{
//缓存线程池 防止太多的线程占据内存
ExecutorService pool= Executors.newCachedThreadPool();
List<List<String>> query = new ArrayList<>();
for (int i = 0; i < 5; i++) {
List<String> list = new ArrayList<>();
switch (i) {
case 0:
list.add("七天酒店");
break;
case 1:
list.add("富力");
break;
case 2:
list.add("北京路");
break;
case 3:
list.add("富力盈凯");
break;
case 4:
list.add("中和广场");
break;
}
query.add(list);
}
String region = "广州";
for (int i = 0; i < query.size(); i++) {
Callable thread = new TestThread(query.get(i),region);
Future<TestObject> f = pool.submit(thread);
System.out.println(f.get().getResult().get(0).get("name"));
System.out.println(f.get().getResult().get(0).get("location"));
}
pool.shutdown();
}
}