add RequestFunctions class

This commit is contained in:
Jack
2024-07-23 02:25:45 -04:00
parent a7b1f7c6e8
commit 36ddb10fe2
3 changed files with 66 additions and 47 deletions

View File

@@ -1,14 +1,10 @@
package io.github.jack1424.realtimeweather.requests;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.naming.ConfigurationException;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.net.ProtocolException;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
@@ -20,23 +16,13 @@ public class SunriseSunsetRequestObject {
private String sunriseTime, sunsetTime;
public SunriseSunsetRequestObject(TimeZone timeZone, String lat, String lon) throws IOException, ParseException, ConfigurationException {
URL url = new URL(String.format("https://api.sunrisesunset.io/json?lat=%s&lng=%s&timezone=UTC", lat, lon));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();
int responseCode = con.getResponseCode();
if (responseCode > 399)
throw new ProtocolException("Server/client error (HTTP error " + responseCode + ")");
Scanner scanner = new Scanner(url.openStream());
StringBuilder data = new StringBuilder();
while (scanner.hasNext()) {
data.append(scanner.nextLine());
JSONObject response;
try {
response = (JSONObject) ((JSONObject) RequestFunctions.makeRequest(String.format("https://api.sunrisesunset.io/json?lat=%s&lng=%s&timezone=UTC", lat, lon))).get("results");
} catch (RequestFunctions.HTTPResponseException e) {
throw new IOException("Server/client error (HTTP error " + e.getMessage() + ")");
}
scanner.close();
JSONObject response = (JSONObject) ((JSONObject) new JSONParser().parse(data.toString())).get("results");
sunriseTime = response.get("sunrise").toString();
sunsetTime = response.get("sunset").toString();