java根据经纬度获取湿度温度
时间: 2023-12-03 19:04:37 浏览: 71
要根据经纬度获取湿度和温度,需要使用气象数据API。以下是一个使用OpenWeatherMap API获取指定地点的湿度和温度的Java示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class WeatherAPI {
public static void main(String[] args) throws Exception {
String apiKey = "YOUR_API_KEY";
String lat = "LATITUDE";
String lon = "LONGITUDE";
String apiUrl = "https://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + apiKey;
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
JSONObject weatherData = new JSONObject(response.toString());
double temperature = weatherData.getJSONObject("main").getDouble("temp");
double humidity = weatherData.getJSONObject("main").getDouble("humidity");
System.out.println("Temperature: " + temperature);
System.out.println("Humidity: " + humidity);
}
}
```
在上述代码中,需要将YOUR_API_KEY替换为您的OpenWeatherMap API密钥,将LATITUDE和LONGITUDE替换为您要查询的地点的纬度和经度。该代码将使用HTTP GET请求向OpenWeatherMap API发出请求并获取响应。然后,它将响应转换为JSON对象,并从中提取温度和湿度数据。最后,它将这些数据打印到控制台上。
阅读全文