Ambient Weather API拉取历史数据异常:仅返回lastdata而非指定时段数据
问题排查与解决
你的核心问题是调用了错误的API端点:当前使用的/v1/devices仅用于获取设备列表及每个设备的最新数据(lastData),它不处理endDate、limit这类历史数据查询参数,因此无论传入什么参数,都只会返回设备的最新状态。
要获取历史数据,必须使用单设备的历史数据专用端点:/v1/devices/{macAddress}/data,其中{macAddress}是你的气象站MAC地址(可从当前返回结果的macAddress字段获取,比如示例中的30:83 ...)。
修正后的代码示例
public static void main(String[] args) throws Exception { String DEVICE_MAC = "30:83:..."; // 替换为你的设备MAC地址 String API_URL = String.format("https://api.ambientweather.net/v1/devices/%s/data", DEVICE_MAC); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, -7); long endDate = calendar.getTimeInMillis(); System.out.println("attempting to pull data using " + endDate + " which is " + new Date(endDate)); int limit = 2; String url = String.format("%s?applicationKey=%s&apiKey=%s&endDate=%s&limit=%s", API_URL, applicationKey, apiKey, endDate, limit); System.out.println("URL [" + url + "]"); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet request = new HttpGet(url); org.apache.hc.client5.http.impl.classic.CloseableHttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String jsonResponse = EntityUtils.toString(entity); System.out.println("output [" + jsonResponse + "]"); // 用专业JSON库解析替代字符串截取,避免出错 ObjectMapper mapper = new ObjectMapper(); List<Map<String, Object>> dataPoints = mapper.readValue(jsonResponse, new TypeReference<List<Map<String, Object>>>() {}); for (Map<String, Object> point : dataPoints) { long dateUtc = Long.parseLong(point.get("dateutc").toString()); System.out.println("received " + dateUtc + " which is " + new Date(dateUtc)); } response.close(); }
额外注意事项
- 确保气象站在一周前有正常数据记录,若设备当时离线,API无法返回对应时段的数据。
- 若要获取一周前到当前的历史数据,可同时指定
startDate(一周前的时间戳)和endDate(当前时间戳),或仅指定startDate,让API返回该时间点到现在的最新2条数据。 - 避免用字符串截取解析JSON,这类方法容错率极低,建议使用Jackson、Gson等专业JSON处理库。
内容的提问来源于stack exchange,提问作者Dale
相关产品推荐
相关产品推荐

