Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

I've had my JPhotoFrame project using the OpenWeatherMap API for some time now, at least since Yahoo messed up its own weather service. I thought it would be useful to share a bit of code on how to use the OWM API, so here it is.

I'm using the OWM JAPIs library, which is compatible with the OWM 2.5 version API.

In order to use OWM programatically, an API key is required. This unfortunately means that the end user has to get their own key too, it's free and not a big deal but is a little bit of an annoyance to have to go through. To get an API key for OWM, first an account is required, one can be created on the OWM sign-up page. After signing up, the API key is available. Update: on the updated site there is an API keys tab.

So here's the bit of code to get a three day forecast and display the minimum and maximum temperature for those days. All of the code is straight forward, it's just a matter of using the right classes.
 OWM Example
public class WeatherTest {
public static final void main(String[] args) {
boolean isMetric = true;
String weatherCity = "Brisbane,AU";
byte forecastDays = 3;
OpenWeatherMap.Units units = (isMetric)
? OpenWeatherMap.Units.METRIC
: OpenWeatherMap.Units.IMPERIAL;
OpenWeatherMap owm = new OpenWeatherMap(units, owmApiKey);
try {
DailyForecast forecast = owm.dailyForecastByCityName(weatherCity, forecastDays);
System.out.println("Weather for: " + forecast.getCityInstance().getCityName());
int numForecasts = forecast.getForecastCount();
for (int i = 0; i < numForecasts; i++) {
DailyForecast.Forecast dayForecast = forecast.getForecastInstance(i);
DailyForecast.Forecast.Temperature temperature = dayForecast.getTemperatureInstance();
System.out.println("\t" + dayForecast.getDateTime());
System.out.println("\tTemperature: " + temperature.getMinimumTemperature() +
" to " + temperature.getMaximumTemperature() + "\n");
catch (IOException | JSONException e) {

This is the output that the code above produces (it's hot in Australia on the first day of 2017!)
Weather for: Brisbane
Sun Jan 01 11:00:00 EST 2017
Temperature: 23.1 to 27.0
Mon Jan 02 11:00:00 EST 2017
Temperature: 23.25 to 30.04
Tue Jan 03 11:00:00 EST 2017
Temperature: 22.25 to 25.1


A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.