728x90
반응형
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeatherExample {
public static void main(String[] args) {
String apiKey="발급받은 키";
String city="Seoul";
String urlString="https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey + "&units=metric";
try{
URL url=new URL(urlString);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
int responseCode=connection.getResponseCode(); // 200
if(responseCode==200){
// 스트림(Stream = 입력,출력)의 연결
BufferedReader in=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer content=new StringBuffer();
while((inputLine=in.readLine())!=null){
content.append(inputLine);
}
in.close();
System.out.println("content.toString() = " + content.toString());
// { }
JsonObject weatherData=JsonParser.parseString(content.toString()).getAsJsonObject();
JsonObject mainData=weatherData.getAsJsonObject("main");
double temp=mainData.get("temp").getAsDouble();
System.out.println("temp = " + temp);
connection.disconnect();
}else{
// 오류 ~~~
}
}catch(Exception e){
e.printStackTrace(); //에러메세지 출력
}
}
}
1. API 키와 URL 설정
String apiKey=" ";
String city="Seoul";
String urlString="https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey + "&units=metric";
- apiKey: OpenWeatherMap API에 접근하기 위한 개인 키.
- city: 날씨 정보를 조회할 도시 이름입. 여기서는 'Seoul'로 설정.
- urlString: API 요청 URL을 구성. units=metric을 추가하여 온도 단위를 섭씨로 설정.
2. HTTP 연결 설정
URL url=new URL(urlString);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
- URL 객체 생성: API 요청 URL을 객체로 만듭니다.
- HttpURLConnection: HTTP GET 요청을 사용하여 서버에 데이터를 요청합니다.
- 헤더 설정: 서버가 JSON 응답을 반환하도록 'Accept' 헤더를 설정합니다.
3. 응답 코드 확인
int responseCode=connection.getResponseCode(); // 200
if(responseCode==200){
- getResponseCode(): 서버 응답 코드(예: 200 OK)를 확인합니다.
- 조건문 검사: 응답 코드가 200(성공)일 때만 데이터를 처리합니다.
4. 데이터 읽기 (JSON 처리 전)
BufferedReader in=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer content=new StringBuffer();
while((inputLine=in.readLine())!=null){
content.append(inputLine);
}
in.close();
- BufferedReader: 서버로부터 전송된 응답 스트림을 읽습니다.
- StringBuffer: 응답 데이터를 저장합니다. (성능 향상)
- 루프 반복: 데이터가 더 이상 없을 때까지 줄 단위로 읽어들이고 content에 추가합니다.
- close(): 스트림을 닫아 자원을 해제합니다.
5. JSON 파싱 및 데이터 추출
JsonObject weatherData=JsonParser.parseString(content.toString()).getAsJsonObject();
JsonObject mainData=weatherData.getAsJsonObject("main");
double temp=mainData.get("temp").getAsDouble();
System.out.println("temp = " + temp);
- Gson 라이브러리 사용: JSON 데이터를 파싱합니다.
- weatherData: 전체 JSON 데이터 객체입니다.
- mainData: 'main' 키에 해당하는 서브 객체를 추출합니다.
- 온도 추출: 'temp' 키에 저장된 값을 double 형태로 가져옵니다.
6. 연결 해제 및 예외 처리
connection.disconnect();
- disconnect(): 연결을 종료하여 자원을 해제합니다.
}catch(Exception e){
e.printStackTrace(); //에러메세지 출력
}
- 예외 처리: 코드 실행 중 오류 발생 시 예외 메시지를 출력합니다.
예상 출력 예시
content.toString() = {"coord":{"lon":126.98,"lat":37.57},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"main":{"temp":15.32,"feels_like":14.86,"temp_min":14.4,"temp_max":16.8,"pressure":1013,"humidity":43}}
temp = 15.32
- 전체 JSON 데이터 출력: JSON 구조를 확인할 수 있습니다.
- 온도 정보 출력: 'temp' 값을 섭씨로 출력합니다.
핵심 요약
- API 요청: URL을 통해 날씨 정보를 가져옵니다.
- JSON 처리: Gson 라이브러리로 JSON 데이터를 객체화합니다.
- 정보 추출: 원하는 키 값을 찾아 데이터를 출력합니다.
728x90
반응형
'웹 백엔드 > 패스트캠퍼스) 백엔드시그니처' 카테고리의 다른 글
패스트캠퍼스) 백엔드시그니처 Course 3 : 웹 개발 입문과 DB (0) | 2025.01.09 |
---|---|
패스트캠퍼스) 백엔드시그니처 Course2: Collection Framwork (0) | 2025.01.02 |
패스트캠퍼스) 백엔드시그니처 Course 2: 자바 API활용하기 및 API 만들기 (0) | 2025.01.02 |
패스트캠퍼스) 백엔드시그니처 Course1: 객체지향 프로그래밍 (0) | 2024.12.30 |
패스트캠퍼스) 백엔드시그니처 Course1: 자바 기초 (0) | 2024.12.30 |