From 6d9a60aef9742e07c8b7ed52d58b2507b49823a7 Mon Sep 17 00:00:00 2001 From: Selim Eser <2211482@stud.hs-mannheim.de> Date: Sat, 8 Jun 2024 22:02:40 +0200 Subject: [PATCH] current_weather method implemented --- .../java/de/hs_mannheim/domain/System.java | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/hs_mannheim/domain/System.java b/src/main/java/de/hs_mannheim/domain/System.java index 1c84e61..14621ac 100644 --- a/src/main/java/de/hs_mannheim/domain/System.java +++ b/src/main/java/de/hs_mannheim/domain/System.java @@ -1,8 +1,17 @@ package de.hs_mannheim.domain; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; import java.util.HashSet; import java.util.TreeSet; +import org.json.JSONObject; + public class System { private User current_user; @@ -48,8 +57,29 @@ public class System { return new String[1]; } - public String current_weather(){ - return ""; + public String current_weather() throws URISyntaxException, IOException, InterruptedException{ + + String weather = "Fehler"; + double temperature = 1; + + HttpClient http_client = HttpClient.newHttpClient(); + + HttpRequest get_request = HttpRequest.newBuilder() + .uri(new URI("https://api.openweathermap.org/data/2.5/weather?zip="+current_user.getZip()+",de&appid="+api_key+"&units=metric&lang=de)")) + .GET() + .build(); + + HttpResponse get_response = http_client.send(get_request, BodyHandlers.ofString()); + + JSONObject json = new JSONObject(get_response.body()); + weather = json.getJSONArray("weather").getJSONObject(0).getString("description"); + temperature = json.getJSONObject("main").getDouble("temp"); + + if(weather.equals("Fehler")) + return "Es ist ein Fehler aufgetreten!"; + else + return weather + ": " + temperature + " °C"; + } public String weather_forecast(String destination_zip){