0

I work at a weather app. I use a free api to get the weather information. When I try yo run this class i get "null" Why?You can see the json code in the url. It should return "Romania" but it returns "null" and I don't know why.

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import org.apache.commons.io.IOUtils;
import org.json.simple.*;
import org.json.simple.parser.ParseException;

public class Weather {
    public static URL url;

    public void getWeather() throws IOException, ParseException {

        url = new URL("http://api.openweathermap.org/data/2.5/weatherq=drobeta,romania");

        Scanner scan = new Scanner(url.openStream());
        String str = new String();
        while (scan.hasNext())
            str += scan.nextLine();
        scan.close();
        System.out.println(str);

        String genreJson = IOUtils.toString(url);
        JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
        // get the title
        System.out.println(genreJsonObject.get("country"));

    }
}
Vitalii Elenhaupt
  • 7,146
  • 3
  • 27
  • 43
  • What do you see if you copy the url and open it in browser? It might be possible that openweathermap.org is blocking your requests if you have exceeded the API quota, although I'm not sure what is their policy. – Marko Gresak May 28 '15 at 21:09
  • check the structure of the json object you have, you will not get a value by doing get(country) – Eddie Martinez May 28 '15 at 21:12

1 Answers1

-2

Putting your url http://api.openweathermap.org/data/2.5/weather?q=drobeta,romania into a browser returned a error 500 for me. I would say this is why your getting the null exception. However if you modify it to http://api.openweathermap.org/data/2.5/weather?q=romania you will get a valid json result.

kodeally
  • 15
  • 3