服务端调用谷歌api根据经纬度计算时区
private String queryTimeZone(String longitude, String latitude)
{
log.info("queryTimeZone.BEGIN={}", JSON.toJSONString(System.currentTimeMillis()));
String sendUrl = "https://maps.googleapis.com/maps/api/timezone/json";
MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
param.add("location",latitude+","+longitude);
param.add("timestamp", String.valueOf((System.currentTimeMillis()/1000)));
param.add("key",Constants.KEY);
ResponseEntity<String> exchange = exchange(sendUrl, param);
String body = exchange.getBody();
log.info("body={}", JSON.toJSONString(body));
TimeZoneEntity timeZoneEntity = JSON.parseObject(body, TimeZoneEntity.class);
log.info("queryTimeZone.END={}", JSON.toJSONString(System.currentTimeMillis()));
return getTimeZone(timeZoneEntity.getTimeZoneId());
}
private ResponseEntity<String> exchange(String sendUrl,MultiValueMap<String,String> param)
{
log.info("queryTimeZone.exchange begin={}", JSON.toJSONString(System.currentTimeMillis()));
log.info("queryTimeZone.exchange sendUrl={}", JSON.toJSONString(sendUrl));
log.info("queryTimeZone.exchange param={}", JSON.toJSONString(param));
HttpHeaders headers = getHttpHeaders();
HttpEntity<MultiValueMap<String,Integer>> entity = new HttpEntity<>(headers);
log.info("queryTimeZone.exchange entity={}",JSON.toJSONString(entity));
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(sendUrl);
URI uri = builder.queryParams(param).build().encode().toUri();
log.info("queryTimeZone.exchange uri={}", JSON.toJSONString(uri));
ResponseEntity<String> exchange = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
log.info("restTemplate.exchange={}",JSON.toJSONString(exchange));
if(null == exchange || 200 != exchange.getStatusCodeValue()){
throw new UnprocessableException(AdvertEnum.DATABASE_DATA_TRUNCATION);
}
log.info("queryTimeZone.exchange end={}", JSON.toJSONString(System.currentTimeMillis()));
return exchange;
}
private HttpHeaders getHttpHeaders()
{
log.info("queryTimeZone.getHttpHeaders begin={}", JSON.toJSONString(System.currentTimeMillis()));
HttpHeaders headers = new HttpHeaders();
// headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
// headers.set("Authorization","Bearer 06a7376573353b3cdb62cacd3b4cc2ab");
log.info("queryTimeZone.getHttpHeaders end={}", JSON.toJSONString(System.currentTimeMillis()));
return headers;
}
private String getTimeZone(String timeZoneId){
log.info("getTimeZone.timeZoneId={}", JSON.toJSONString(timeZoneId));
if(StringUtils.isEmpty(timeZoneId)){
return null;
}
List<TimeZoneVO> timeZoneList = pileBaseAdapter.getTimeZoneList();
if (CollectionUtils.isNotEmpty(timeZoneList)){
for (TimeZoneVO timeZoneVO : timeZoneList) {
for (String str : timeZoneVO.getZoneIdList()){
if (str.equals(timeZoneId)){
return timeZoneVO.getCode();
}
}
}
}
return null;
}