Java-Based Weather Forecasting: Real-Time Data Fetching using OpenWeatherMap API
This project aims to develop a java application that fetches and displays real-time weather data using the OpenWeatherMap API. This will allow users to input a location and will then retrieve and display the current weather conditions.
Code:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; public class WeatherData { private static final String API_KEY = "b2f570d96d0cc4d1465599ecbeb7747d"; private static final String API_URL = "http://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s"; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the name of the city: "); String city = scanner.nextLine(); try { String url = String.format(API_URL, city, API_KEY); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println("Raw Weather Data for " + city + ": " + response.toString()); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } }
Output:
Enter the name of the city: Bengaluru Raw Weather Data for Bengaluru: {"coord":{"lon":77.6033,"lat":12.9762}, "weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}], "base":"stations", "main":{"temp":298.73, "feels_like":299.46,"temp_min":297.05, "temp_max":298.95,"pressure":1015,"humidity":81}, "visibility":6000, "wind":{"speed":3.09,"deg":220}, "clouds":{"all":40},"dt":1717735283, "sys":{"type":1,"id":9205,"country":"IN","sunrise":1717719761, "sunset":1717766072}, "timezone":19800,"id":1277333, "name":"Bengaluru","cod":200}.