티스토리 뷰

728x90
반응형

 

JSON 형식의 API를 호출 할 때 사용 가능합니다.

 

아래는 응답메세지를 text라는 문자열로 저장하는 코드입니다.

공공데이터포털, 서울 열린데이터광장에는 코드별로 API 호출예시가 있어 참고하였습니다. ( 소스코드 동일)

예전에는 공공데이터포털에 API마다 샘플코드가 있었는데, 최근에 사라진 듯 합니다.

 

서울 열린데이터 광장 API openAPI 샘플코드 예시 (최하단으로 스크롤)

https://data.seoul.go.kr/together/guide/useGuide.do

 

열린데이터광장 메인

데이터분류,데이터검색,데이터활용

data.seoul.go.kr

 

// stringURL 에는 API URL 넣기
URL url = new URL(stringURL);
String line;
StringBuilder sb = new StringBuilder();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/json; charset=UTF-8");

// API 응답메시지를 불러와서 문자열로 저장
BufferedReader rd;
if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
    rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
} else {
    rd = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
}
while ((line = rd.readLine()) != null) {
    sb.append(line);
}
rd.close();
conn.disconnect();
String text = sb.toString();

 

 

이제 텍스트로 저장된 응답메세지를 list 혹은 map으로 바꿔줍니다.

응답메세지가 map 타입이면 map으로,

list 타입이라면 새 map을 생성해서 "data"라는 키의 벨류로 넣어주었습니다.

try {
    Map<String, Object> map = mapper.readValue(text, Map.class);
}catch(Exception e) {
    List<String> data = mapper.readValue(text, List.class);
    Map<String, Object> map = new HashMap<>();
    map.put("data", data);
}

 

 

 

호출할 API가 많다면,

아래와 같이 API를 호출하는 코드를 메소드로 만들어놓고 사용하시면 됩니다.

getApi(호출할 API URL)을 넣으면 API 응답메세지를 Map 타입으로 리턴받게 됩니다.

 

// 전체코드
public Map<String, Object> getApi(String stringURL) throws IOException{
    URL url = new URL(stringURL);
    String line;
    StringBuilder sb = new StringBuilder();
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Content-type", "application/json; charset=UTF-8");


    BufferedReader rd;
    if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    } else {
        rd = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
    }
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();
    conn.disconnect();
    String text = sb.toString();

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    mapper.enable(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS.mappedFeature());

    try {
        Map<String, Object> map = mapper.readValue(text, Map.class);
        return map;
    }catch(Exception e) {
        List<String> data = mapper.readValue(text, List.class);
        Map<String, Object> map = new HashMap<>();
        map.put("data", data);
        return map;
    }

}

 

 

 

만약 POST로 호출해야 한다면,

URL을 호출하기 전에 파라미터(요청변수)들을 먼저 설정하고 함께 전달하면 됩니다.

 

URL obj = null;
// 파라미터를 postData에 넣음
StringBuilder postData = new StringBuilder();

// params는 파라미터 키와 값들이 들어있는 Map
for(Map.Entry<String,Object> param : params.entrySet()) {
    if(postData.length() != 0) postData.append('&');
    postData.append(param.getKey());
    postData.append('=');
    postData.append(param.getValue());
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
// URL을 호출함
obj = new URL(stringURL);
HttpURLConnection con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
con.setDoOutput(true);
con.getOutputStream().write(postDataBytes);

BufferedReader in = new BufferedReader(
        new InputStreamReader(con.getInputStream(), "UTF-8"));
String line;
StringBuffer sb = new StringBuffer();
while((line = in.readLine()) != null){
    sb.append(line);
}
in.close();

String text = sb.toString();

 

728x90
반응형
댓글