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

@@ -2,46 +2,34 @@ package io.github.jack1424.realtimeweather.requests;
import org.json.simple.JSONArray;
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.util.Scanner;
public class WeatherRequestObject {
private boolean rain = false, thunder = false;
public WeatherRequestObject(String apiKey, String lat, String lon) throws IOException, ParseException, ConfigurationException {
URL url = new URL(String.format("https://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&appid=%s", lat, lon, apiKey));
JSONArray conditions;
try {
conditions = (JSONArray) ((JSONObject) RequestFunctions.makeRequest(String.format("https://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&appid=%s", lat, lon, apiKey))).get("weather");
} catch (RequestFunctions.HTTPResponseException e) {
int responseCode = Integer.parseInt(e.getMessage());
if (responseCode > 499) {
throw new ProtocolException("Server/client error (HTTP error " + responseCode + ")");
} else if (responseCode > 399) {
String message = "Error when getting weather information: ";
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();
int responseCode = con.getResponseCode();
if (responseCode > 499) {
throw new ProtocolException("Server/client error (HTTP error " + responseCode + ")");
if (responseCode == 401)
throw new ConfigurationException(message + "API key invalid. Check the Wiki for troubleshooting steps.");
else
throw new ProtocolException(message + "Unknown error");
} else {
throw new IOException("Server/client error (HTTP error " + e.getMessage() + ")");
}
}
else if (responseCode > 399) {
String message = "Error when getting weather information: ";
if (responseCode == 401)
throw new ConfigurationException(message + "API key invalid. Check the Wiki for troubleshooting steps.");
else
throw new ProtocolException(message + "Unknown error");
}
Scanner scanner = new Scanner(url.openStream());
StringBuilder data = new StringBuilder();
while (scanner.hasNext()) {
data.append(scanner.nextLine());
}
scanner.close();
JSONArray conditions = (JSONArray) ((JSONObject) new JSONParser().parse(data.toString())).get("weather");
for (Object rawCondition : conditions) {
int id = Integer.parseInt(String.valueOf(((JSONObject) rawCondition).get("id")));