-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeather.java
More file actions
90 lines (74 loc) · 2.98 KB
/
Copy pathWeather.java
File metadata and controls
90 lines (74 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.cs2212;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.simple.*;
import org.json.simple.parser.*;
/**
* This class represents a Weather object that retrieves and stores the current weather and condition for a given city.
* @author rrenv
*/
public class Weather {
private String city;
private double currWeather;
private String currCondition;
private static final String key = "205962d59a6c491b89d50234231602";
private static final String URL = "http://api.weatherapi.com/v1/current.json?key=205962d59a6c491b89d50234231602&q=43.0096,-81.2737&aqi=no";
/**
* Constructs a new Weather object for the given city.
* @param city the name of the city for which to retrieve weather information
*/
public Weather (String city) {
this.city = city;
try {
URL link = new URL(URL);
HttpURLConnection con = (HttpURLConnection) link.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Scanner scanner = new Scanner(con.getInputStream());
String response = scanner.useDelimiter("\\A").next();
scanner.close();
// Parse the JSON response
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(response);
/* If location changes:
JSONObject location = (JSONObject) jsonObject.get("location");
String city = (String)location.get("name");
*/
JSONObject current = (JSONObject) jsonObject.get("current");
currWeather = (double)current.get("temp_c");
JSONObject condition = (JSONObject)current.get("condition");
currCondition = (String)condition.get("text");
}
} catch (Exception e) {
System.out.println("Error recovering weather details.");
city = "Error ";
currWeather = 1;
currCondition = ": weather details available.";
currWeather = 1;
currCondition = "No internet.";
}
}
/**
* Returns the name of the city for which this Weather object has retrieved information.
* @return the name of the city
*/
public String getCity() {
return city;
}
/**
* Returns the current temperature in Celsius for the city represented by this Weather object.
* @return the current temperature in Celsius
*/
public double getCurrWeather() {
return currWeather;
}
/**
* Returns a text description of the current weather conditions for the city represented by this Weather object.
* @return a text description of the current weather conditions
*/
public String getCurrCondition() {
return currCondition;
}
}