:::: 개발 ::::/::: JAVA :::

공공 data api HttpURLConnection 500 애러 발생 해결

nayha 2020. 10. 21. 10:13
반응형
urlBuilder.append("&" + URLEncoder.encode("_type","UTF-8") + "=" + URLEncoder.encode("json", "UTF-8"));

파라미터에 타입 추가하면 해결 !!

 

전체 소스

 

/* Java 샘플 코드 */


import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.IOException;

public class ApiExplorer {
    public static void main(String[] args) throws IOException {
        StringBuilder urlBuilder = new StringBuilder("http://openapi.airport.kr/openapi/service/StatusOfPassengerFlights/getPassengerArrivals"); /*URL*/
        urlBuilder.append("?" + URLEncoder.encode("ServiceKey","UTF-8") + "=서비스키"); /*Service Key*/
        urlBuilder.append("&" + URLEncoder.encode("from_time","UTF-8") + "=" + URLEncoder.encode("0000", "UTF-8")); /*검색 시작 시간 (HHMM)*/
        urlBuilder.append("&" + URLEncoder.encode("to_time","UTF-8") + "=" + URLEncoder.encode("2400", "UTF-8")); /*검색 종료 시간 (HHMM)*/
        urlBuilder.append("&" + URLEncoder.encode("airport","UTF-8") + "=" + URLEncoder.encode("  HKG", "UTF-8")); /*출발지 공항 코드*/
        urlBuilder.append("&" + URLEncoder.encode("flight_id","UTF-8") + "=" + URLEncoder.encode("  KE846", "UTF-8")); /*운항 편명*/
        urlBuilder.append("&" + URLEncoder.encode("airline","UTF-8") + "=" + URLEncoder.encode("  KE", "UTF-8")); /*항공사 코드*/
        urlBuilder.append("&" + URLEncoder.encode("lang","UTF-8") + "=" + URLEncoder.encode(" K", "UTF-8")); /*국문=K, 영문=E, 중문=C, 일문=J, Null=K*/
        URL url = new URL(urlBuilder.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/json");
        System.out.println("Response code: " + conn.getResponseCode());
        BufferedReader rd;
        if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        } else {
            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        }
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
        conn.disconnect();
        System.out.println(sb.toString());
    }
}
반응형