레이블이 Java로 기상정보 조회만들기인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Java로 기상정보 조회만들기인 게시물을 표시합니다. 모든 게시물 표시

2017년 6월 12일 월요일

6. JAVA로 날씨정보, 대기정보 호출...


1. 대기정보 분해하기

2. 수치 값이 오기에, 한국 사이트에서 값 구간에 대한 문자열 값을 보고 출력해 줌.

public static void parseAir(String airInfo) {
  try {
   ObjectMapper mapper = new ObjectMapper();
   JsonNode root = mapper.readTree(airInfo);
   System.out.println(root.path("data"));
   System.out.println(root.path("data").path("aqi"));
   String aqiVal = root.path("data").path("aqi").toString();
   int aqi = Integer.parseInt(aqiVal);
   String aqiNm = "";
   if(aqi <= 0 && aqi >=50) aqiNm = "좋음";
   if(aqi <= 51 && aqi >=100) aqiNm = "보통";
   if(aqi <= 101 && aqi >=150) aqiNm = "민감군영향";
   if(aqi <= 151 && aqi >=200) aqiNm = "나쁨";
   if(aqi <= 201 && aqi >=300) aqiNm = "매우나쁨";
   if(aqi < 300) aqiNm = "위험";
   System.out.println(aqiNm);
   //System.out.println(root.path("result"));
   /*
    * 
   AQI 지수구분 구간의미
   0 - 50 좋음 대기오염 관련 질환자군에서도 영향이 유발되지 않을 수준
   51 -100 보통 환자군에게 만성 노출시 경미한 영향이 유발될 수 있는 수준
   101-150 민감군영향 환자군 및 민감군에게 유해한 영향이 유발될 수 있는 수준
   151-200 나쁨 환자군 및 민감군(어린이, 노약자 등)에게 유해한 영향 유발, 일반인도 건강상 불쾌감을 경험할 수 있는 수준
   201-300 매우나쁨 환자군 및 민감군에게 급성 노출시 심각한 영향 유발, 일반인도 약한 영향이 유발될 수 있는 수준
   300+ 위험 환자군 및 민감군에게 응급 조치가 발생되거나, 일반인에게 유해한 영향이 유발될 수 있는 수준
    * 
    */
  } catch (JsonProcessingException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
 }

5. JAVA로 날씨정보, 대기정보 호출...

1. 날씨정보 분해하기

2. json 사용할 줄 알면 다 하는 그거..

3. jackson 2.8.9 사용함.
public static void parseWeather(String weatherInfo) {
  //System.out.println(weatherInfo);
  try {
   ObjectMapper mapper = new ObjectMapper();
   JsonNode root = mapper.readTree(weatherInfo);
   //System.out.println(root.path("weather"));
   System.out.println(root.path("weather").path("yesterday").get(0).findValue("sky")); //여러 정보가 오지만.. 난 날씨만 필요함
   System.out.println(root.path("result"));
  } catch (JsonProcessingException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
 }

4. JAVA로 날씨정보, 대기정보 호출...

1. url에서 읽어온 InputStream을 String 변환 공통 함수

2. 인터넷에서 대충 줒은거 개조했음.


public static void printByInputStream(InputStream is, String tgtMode) {
  byte[] buf = new byte[2048];
  StringBuffer sb = new StringBuffer();
  int len = -1;
  try {
   while ((len = is.read(buf, 0, buf.length)) != -1) {
    sb.append(new String(buf, 0, len));
   }   
   
   System.out.println(sb.toString());
   
   if(tgtMode.equals("weather")){
    parseWeather(sb.toString());
   }else{
    parseAir(sb.toString());
   }
   
  } catch (IOException e) {
   e.printStackTrace();
  }  
 }

3. JAVA로 날씨정보, 대기정보 호출...

1. 대기정보값 받기..


public static void getAir(String lat, String lon){
  httpclient = HttpClients.createDefault();
  String callUrl = setLocation(lat, lon, "air");
  try {
   HttpGet httpGet = new HttpGet(callUrl);     //대기정보 url 호출...
   httpGet.addHeader("appKey", appKeyId);
   System.out.println(httpGet.getURI());
   System.out.println("[Executing request]: " + httpGet.getRequestLine());

   HttpResponse response = httpclient.execute(httpGet);

   //System.out.println(response.toString());
   InputStream in2;
   in2 = response.getEntity().getContent();
   printByInputStream(in2 , "air");
   in2.close();
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   
  }
 }

2. JAVA로 날씨정보, 대기정보 호출...

1. 위치 설정 API 값 지정하기...


public static String setLocation(String lat, String lon, String flagStr){
  String callUrl = "";
  if(flagStr.equals("weather")){  //날씨정보일땐 SK 대기정보는 aqi 에서...
   callUrl = "http://apis.skplanetx.com/weather/history/yesterday?version=" + Version + "&lat=" + lat + "&lon=" + lon;
  }else{
   callUrl = "http://api.waqi.info/feed/geo:"+lat+";"+lon+"/?token=" + aqicnToken;
  }
  
  return callUrl;  
 }

1. JAVA로 날씨정보, 대기정보 호출...

1. 일단 날씨정보부터...

2. SK 플래닛에서 키발급 받아라!! (알아서 재주껏) 

3. 통신은 Apache HttpClients 4.4로 했음.
public static void getWeather(String lat, String lon){
  httpclient = HttpClients.createDefault();

                String lat = "37.589470";      //조회하고 싶은 위도 경도, 구글 맵에서 값 구하는 것은 상식!
  String lon = "126.673081";

  String callUrl = setLocation(lat, lon, "weather"); //위치 설정 (위도, 경도, return mode) 날씨인지, 대기정보인지...
  
  try {
   HttpGet httpGet = new HttpGet(callUrl);
   httpGet.addHeader("appKey", appKeyId); //발급받은 키를 헤더에 태워서 같이 날려줘야 함..
   //System.out.println(httpGet.getURI());
   //System.out.println("[Executing request]: " + httpGet.getRequestLine());

   HttpResponse response = httpclient.execute(httpGet);

   //System.out.println(response.toString());
   InputStream in;
   in = response.getEntity().getContent();
   printByInputStream(in, "weather");
   in.close();
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
  }
 }

0. JAVA로 날씨정보, 대기정보 호출...

기상정보를 쓸 프로그램을 할 일이 생겨서.. 급 조사후 코딩 중.. 대략 구글링을 해보니..

1. 기상청에서 정보제공하는 건 못써먹을 수준 또는 계속 대기 중..(역시 정부기관이라 느려터짐)

2. SK플래닛 날씨정보 쓰라고 추천

3. 키 부여 받고 테스트 개발해 봄.

4. 내가 멍청한건지... API 문서가 부실한건지(아니야.. 난 안 멍청한걸꺼야.. ㅜ_ㅜ) 조금 헤매다가 하여간 구현 성공..

5. 미세먼지 정보도 받으려고 했으나 계속 에러.. 

6. 요청횟수 오류 어쩌고 나오고 SLA 레벨을 올리라고 나오길래 설정 들어가 보니...

7. 날씨조회는 일일 1000번(이 정도까지 쓸 생각 없다!)

8. 미세먼지 정보는 일일 0번(!!!!!!!) -->; 이거 돈 받고 오픈하는구나 란 생각이 팍 듬!!! (역시 자본주의 만세!!)

9. 다른거 이래저래 봤으나, 국내 API는 답 없는 듯..

10. 날씨만 SK꺼 쓰고, 미세먼지/대기정보는 외국꺼 쓰기로 결론(우훗~~ 포기가 빠른 남자~) 

11. 다행히도 http://aqicn.org 란 사이트가 있네.. 이것도 키 발급 받고 바로 개발시작!!

12. SK꺼 보다 더 간단함.

13. 내꺼 긁어갔으면.. 좀 긁어갔다고 출처는 밝히자.. 나도 먹고살게.


끗~~~ 애보러 가야지~

[낯선] 2026.06.20 이태원 MZK MuzikBar 공연

간만의 공연 이태원 비틀즈가 이전하여 MZK MuzikBar 로 새 단장 오픈을 한 뒤로 2번째 공연 새 베이시스트가 합류한 뒤로 첫 공연이기도 함.. 이래저래 틀린 부분도 많지만.. 그래도 간만에 그럭저럭 잘했다.. https://www.youtub...