java如何獲取天氣狀況代碼

要獲取天氣狀況,你可以使用一些公開的天氣API服務,如OpenWeatherMap、Weatherstack等。以下是一個使用Java和OpenWeatherMap A...
要獲取天氣狀況,你可以使用一些公開的天氣API服務,如OpenWeatherMap、Weatherstack等。以下是一個使用Java和OpenWeatherMap API獲取天氣狀況的簡單示例。
你需要注冊一個OpenWeatherMap賬戶并獲取一個API密鑰。
以下是使用Java和OpenWeatherMap API獲取天氣狀況的步驟:
1. 添加OpenWeatherMap的依賴(如果你使用的是Maven,可以在pom.xml中添加以下依賴):
```xml
```
2. 編寫Java代碼:
```java
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeatherExample {
public static void main(String[] args) {
String apiKey = "YOUR_API_KEY"; // 替換為你的OpenWeatherMap API密鑰
String city = "London"; // 你想查詢的城市
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey + "&units=metric";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
本文鏈接:http:///bian/354961.html
上一篇:如何刪除電腦最近訪問記錄刪除不了
下一篇:海濱的濱怎么組詞3個詞