PRA2024/projekt_1/src/main/java/org/adamgulczynski/DataFetcher.java

53 lines
1.5 KiB
Java

package org.adamgulczynski;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DataFetcher {
private final String apiKey;
public DataFetcher(String apiKey) {
this.apiKey = apiKey;
}
public String fetchWeather(double latitude, double longitude) throws IllegalArgumentException {
if (latitude > 90 || latitude < -90) {
throw new IllegalArgumentException();
} else if (longitude > 180 || longitude < -180) {
throw new IllegalArgumentException();
}
String urlStr = "https://api.openweathermap.org/data/2.5/weather?lat="
+ latitude + "&lon=" + longitude + "&appid=" + this.apiKey;
try {
URL url = new URL(urlStr);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to GET
connection.setRequestMethod("GET");
// Read the response from the server
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}