Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class app
- {
- private static String urlString;
- private static URL url = null;
- public static void main(String[] args) throws IOException
- {
- String urlStr= "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=c6af9bbd12814081994190330191301&q=";
- String city = args[0];
- String days = args[1];
- urlString = urlStr + URLEncoder.encode(city, "UTF8")+"&format=json&num_of_days=" + URLEncoder.encode(days, "UTF8");
- BufferedReader reader= null;
- HttpURLConnection connection = null;
- StringBuilder stringBuilder = new StringBuilder();
- String line =null;
- try
- {
- url = new URL(urlString);
- }
- catch(MalformedURLException e)
- {
- System.out.println("URL Error");
- }
- try
- {
- connection = (HttpURLConnection)url.openConnection();
- connection.setRequestMethod("GET");
- connection.setReadTimeout(15*100000);
- connection.connect();
- }
- catch(NullPointerException e)
- {
- System.out.println("Connection error");
- }
- try
- {
- reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- while((line = reader.readLine()) != null)
- {
- stringBuilder.append(line);
- }
- }
- catch(NullPointerException e)
- {
- System.out.println("Reader error");
- }
- String jsonString = stringBuilder.toString();
- if(reader!=null)
- reader.close();
- try
- {
- JsonObject jsonObj = new JsonParser().parse(jsonString).getAsJsonObject();
- JsonObject jsonData = jsonObj.getAsJsonObject("data");
- JsonArray jsonArray = jsonData.getAsJsonArray("request");
- for(int i = 0;i<jsonArray.size();i++)
- {
- String postId = jsonArray.get(i).getAsJsonObject().get("query").getAsString();
- System.out.println(postId);
- }
- jsonArray = jsonData.getAsJsonArray("weather");
- for(int i = 0;i<jsonArray.size();i++)
- {
- String postId = jsonArray.get(i).getAsJsonObject().get("date").getAsString();
- String postId2 = jsonArray.get(i).getAsJsonObject().get("mintempC").getAsString();
- String postId3 = jsonArray.get(i).getAsJsonObject().get("maxtempC").getAsString();
- System.out.println(postId + " temperatura min = " + postId2 + ", temperatura max = " + postId3);
- }
- }
- catch(IllegalStateException e)
- {
- System.out.println("Json object error");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement