OpenWeather API에서 Current Weather Data를 구독해주면 된다. Free 티어 API key를 발급받고, api keys 여기에서 발급받은 키를 확인할 수 있다.
자세한 내용은 current docs 이 곳을 확인!
java.net.MalformedURLException: no protocol:api.openweathermap.org/data/2.5...
오류가 발생하므로 http를 앞에 붙여준다.http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
서울이 latitude=37.517235, longitude=127.047325래서 대충 37, 127로 적었더니 평양이 나온다...ㅎㅎ
lat=37.517&lon=127.04 이렇게 두면 잠원동이 나오길래 여기를 기준으로 찾아보도록 하겠다.
@RestController
public class weatherController {
private String key = "{your api key}";
@GetMapping("/weather/{lon}/{lat}")
public String getWeather(@PathVariable String lat, @PathVariable String lon){
StringBuilder stringBuilder = new StringBuilder();
try {
String APIUrl = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + key;
URL url = new URL(APIUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-type", "application/json");
BufferedReader bufferedReader;
if(urlConnection.getResponseCode() >= 200 && urlConnection.getResponseCode() <= 300) {
bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
}
else {
bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getErrorStream()));
}
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
bufferedReader.close();
urlConnection.disconnect();
} catch (Exception e){
e.printStackTrace();
}
return stringBuilder.toString();
}
}
{
coord: {
lon: 127.04,
lat: 37.517
},
weather: [
{
id: 800,
main: "Clear",
description: "clear sky",
icon: "01d"
}
],
base: "stations",
main: {
temp: 271.93,
feels_like: 266.62,
temp_min: 271.82,
temp_max: 272.85,
pressure: 1032,
humidity: 19
},
visibility: 10000,
wind: {
speed: 5.14,
deg: 340
},
clouds: {
all: 0
},
dt: 1645599304,
sys: {
type: 1,
id: 8096,
country: "KR",
sunrise: 1645567932,
sunset: 1645607921
},
timezone: 32400,
id: 1846735,
name: "Jamwon-dong",
cod: 200
}