1、批量算路功能
本次使用的是RestTemplate来发起get请求,用ResponseEntity来接受返回数据(正确):
ResponseEntity forEntity = restTemplate.getForEntity(new URI(url),String.class);
因为之前常遇到的返回数据一般为json格式,因此一开始的定义为Map格式来接收(错误):
ResponseEntity forEntity = restTemplate.getForEntity(new URI(url),Map.class);
会定义Map来接收是因为想要直接转为Map来使用较为方便,另外也是因为官方给出的请求参数中output写明了返回的是json或者xml:
后来在postman中测试发现返回的是text/js类型的数据:
而在IDEA中完整报错是:
org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class java.lang.Object] and content type [text/html]
意思为无法适配接收的数据,返回的数据类型是:[text/html]
因此接收类型改为String.class。
接收的String数据是JSON样式的字符串,因此用转换工具将此String转为Map,后续也可以再用JSONArray来处理,都可:
ResponseEntity forEntity = restTemplate.getForEntity(new URI(url),String.class);
String body = (String) forEntity.getBody();
Map map = StringToMapUtil.strJsonToMap(body);
JSONArray js = (JSONArray) map.get("result");
JSONObject jsonObject = js.getJSONObject(0);
routeTime = (String) ((JSONObject) jsonObject.get("duration")).get("text");
routeDistance = (String) ((JSONObject) jsonObject.get("distance")).get("text");
================================2022.4.12=================================