forked from Vanshikapandey30/Hacktoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetches_weather_information_from_a_hypothetical_API.java
70 lines (58 loc) · 2.51 KB
/
fetches_weather_information_from_a_hypothetical_API.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class WeatherApp {
// API key for the weather service
private static final String API_KEY = "your_api_key";
private static final String BASE_URL = "https://api.openweathermap.org/data/2.5/weather?q=";
// Method to fetch weather data
public static String getWeatherData(String city) {
String response = "";
try {
// Construct the API URL
String apiUrl = BASE_URL + city + "&appid=" + API_KEY + "&units=metric"; // For Celsius
// Establish a connection to the API
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// Read the API response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
// Close connection
connection.disconnect();
response = content.toString();
} catch (Exception e) {
System.out.println("Error occurred: " + e.getMessage());
}
return response;
}
// Method to parse and display weather data
public static void displayWeather(String city) {
String weatherData = getWeatherData(city);
try {
// Parse JSON response
JSONObject jsonObject = new JSONObject(weatherData);
String cityName = jsonObject.getString("name");
JSONObject main = jsonObject.getJSONObject("main");
double temperature = main.getDouble("temp");
String weatherDescription = jsonObject.getJSONArray("weather").getJSONObject(0).getString("description");
// Display weather information
System.out.println("City: " + cityName);
System.out.println("Temperature: " + temperature + "°C");
System.out.println("Weather: " + weatherDescription);
} catch (Exception e) {
System.out.println("Error parsing weather data: " + e.getMessage());
}
}
public static void main(String[] args) {
// Example: fetch weather for Colombo
displayWeather("Colombo");
}
}