Introduction
In today’s world, getting weather information instantly is crucial for various applications, whether it be for planning travel, daily activities, or for general curiosity. The objective of this program is to fetch weather information from an external weather API and display it to the user.
In this program, we will utilize a free weather API such as OpenWeatherMap or Weatherstack to fetch real-time weather data. The user will input the city name, and the program will return the weather details such as temperature, humidity, weather description, etc.
Objective
The goal of this program is to:
- Fetch weather information for a user-specified city from an external API.
- Display the fetched weather information, such as temperature, humidity, weather description, and more.
- Provide a simple and interactive way for users to obtain current weather data from an API in Java.
Code
import java.io.InputStreamReader; import java.io.BufferedReader; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; public class WeatherFetcher { // Replace with your API key from OpenWeatherMap or any other weather service private static final String API_KEY = "YOUR_API_KEY"; private static final String BASE_URL = "http://api.openweathermap.org/data/2.5/weather?q="; public static void main(String[] args) { // Prompt user to enter the city System.out.println("Enter the city name: "); BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(System.in)); try { String city = reader.readLine().trim(); String urlString = BASE_URL + city + "&appid=" + API_KEY + "&units=metric"; // Fetch data in metric units String response = getWeatherData(urlString); parseAndDisplayWeather(response); } catch (Exception e) { System.out.println("Error fetching weather data: " + e.getMessage()); } } // Method to make the API request and get the response as a String private static String getWeatherData(String urlString) throws Exception { URL url = new URL(urlString); 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(); return response.toString(); } // Method to parse the JSON response and display weather information private static void parseAndDisplayWeather(String response) { JSONObject jsonResponse = new JSONObject(response); if (jsonResponse.getInt("cod") == 200) { // Check if the API call was successful JSONObject main = jsonResponse.getJSONObject("main"); JSONObject weather = jsonResponse.getJSONArray("weather").getJSONObject(0); String description = weather.getString("description"); double temperature = main.getDouble("temp"); int humidity = main.getInt("humidity"); System.out.println("Weather in " + jsonResponse.getString("name") + ":"); System.out.println("Description: " + description); System.out.println("Temperature: " + temperature + "°C"); System.out.println("Humidity: " + humidity + "%"); } else { System.out.println("Error: Unable to fetch weather data for the specified city."); } } }
Program Explanation
This Java program is designed to fetch and display weather information from an external API. Below is an explanation of its components:
- API Key and URL: We use the OpenWeatherMap API for fetching weather data. You need to replace the placeholder
YOUR_API_KEY
with your actual API key obtained from OpenWeatherMap or another weather service provider. - User Input: The program prompts the user to input a city name. This city name is used to query the weather API for the relevant weather data.
- Fetching Data: The
getWeatherData
method makes an HTTP GET request to the OpenWeatherMap API, passing the city name, API key, and metric units (Celsius) for temperature. - Parsing JSON Response: The JSON response from the API is parsed using the
org.json.JSONObject
class. It extracts information such as the weather description, temperature, and humidity, and then displays it to the user. - Error Handling: The program includes basic error handling to catch issues such as an invalid city name or API request failure. If the response code is not 200 (success), the program will display an error message.
How to Run the Program
Follow these steps to run the program:
- Obtain an API key from OpenWeatherMap (or another weather API provider). Sign up for free at OpenWeatherMap to get your API key.
- Save the code in a file named
WeatherFetcher.java
. - Replace
YOUR_API_KEY
with your actual API key in the code. - Open a terminal or command prompt and navigate to the directory where the file is saved.
- Compile the program with the Java compiler:
javac WeatherFetcher.java
- Run the program:
java WeatherFetcher
- The program will ask for the name of a city. Enter the city, and the weather information will be displayed.