人妻系列无码专区av在线,国内精品久久久久久婷婷,久草视频在线播放,精品国产线拍大陆久久尤物

當前位置:首頁 > 編程技術 > 正文

java如何獲取天氣狀況代碼

java如何獲取天氣狀況代碼

要獲取天氣狀況,你可以使用一些公開的天氣API服務,如OpenWeatherMap、Weatherstack等。以下是一個使用Java和OpenWeatherMap A...

要獲取天氣狀況,你可以使用一些公開的天氣API服務,如OpenWeatherMap、Weatherstack等。以下是一個使用Java和OpenWeatherMap API獲取天氣狀況的簡單示例。

你需要注冊一個OpenWeatherMap賬戶并獲取一個API密鑰。

以下是使用Java和OpenWeatherMap API獲取天氣狀況的步驟:

1. 添加OpenWeatherMap的依賴(如果你使用的是Maven,可以在pom.xml中添加以下依賴):

```xml

org.json

json

20210307

```

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);