[JAVA] HttpURLConnection 으로 REST API 요청하기 (feat. Ncloud API - geocode)

seonjeong·2023년 5월 11일

Java

목록 보기
19/26
post-thumbnail

💖 HttpURLConnection

  • HTTP 통신을 가능케 해주는 클래스
  • URL 객체에서 연결을 통해 HttpURLConnection 인스턴스를 얻는다

    HTTP requset와 response 구성
    - Header : 데이터의 정보를 담는다
    - Body : 데이터를 담는다


🔥 URL 객체 생성

주어진 URL주소에 대해 새 URL객체를 생성한다

URL url = new URL("주소");

🔥 URL에서 HttpURLConnection 객체 얻기

URL객체의 openConnection() 객체의 메소드 호출에 의하여 얻어진다

HttpURLConnection con = (HttpURLConnection)url.openConnection();

🔥 URLConnection 구성

실제로 연결을 설정하기 전에 클라이언트와 서버 간의 다양한 옵션을 설정할 수 있다

  • setRequestProperty(String key, String value) : key, value 쌍으로 지정된 일반 요청 속성을 설정
  • setRequestMethod(String method) : HTTP 메소드 GET, POST 등 중 하나인 URL요청에 대한 메소드 설정. 기본값은 GET

🔥 헤더 필드 읽기

연결이 이루어지면 서버는 URL요청을 처리하고 메타데이터와 실제 콘텐츠로 구성된 응답을 다시 보낸다

메타데이터 : 헤더 필드라고 하는 key, value 쌍의 모음
헤더 필드 : 서버에 대한 정보, 상태 코드, 프로토콜 정보 등을 나타냄

  • getResponseCode() : 서버에서 보낸 HTTP 상태 코드 반환

🔥 입력 스트림 가져오기 및 데이터 읽기

실제 내용을 읽으려면 연결에서 inputStream인스턴스를 얻어야 한다

// 데이터를 문자열로 읽기 위해 BufferedReader로 래핑
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

더 자세한 내용은 아래의 블로그를 참조
https://blueyikim.tistory.com/2199


전체코드

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test {
    public static void main(String[] _args) throws Exception {
        // 1. 장치에 요청할 URI를 입력한다.
        URL url = new URL("http://httpbin.org/get");
        HttpURLConnection con = (HttpURLConnection)url.openConnection();

        con.setRequestProperty("Content-Type", "application/json");

        // 2. Method 타입을 정의하고 API를 전송한다.
        con.setRequestMethod("GET");
        con.getResponseCode();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        System.out.println(response.toString());
    }
}



💖 Ncloud API - geocode

주소를 입력하면 좌표를 반환받고 싶어서 네이버 클라우드 API인 geocode를 이용하였다.
문서에서는 CURL방식으로만 나와있어서 URLHttpConnection을 이용한 방법으로 바꿔서 호출하였다.

https://api.ncloud-docs.com/docs/ai-naver-mapsgeocoding-geocode

CURL

curl -G "https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode" \
    --data-urlencode "query={주소}" \
    --data-urlencode "coordinate={검색_중심_좌표}" \
    -H "X-NCP-APIGW-API-KEY-ID: {애플리케이션 등록 시 발급받은 client id값}" \
    -H "X-NCP-APIGW-API-KEY: {애플리케이션 등록 시 발급받은 client secret값}" -v

적용코드

public String getGeometricData(String address) {
  String clientId = "아이디";
  String clientSecret = "비번";

  StringBuffer response = null;

  // 장치에 요청할 URI
  try {

    String encodedQuery = URLEncoder.encode(address, "UTF-8"); // 입력받은 주소를 인코딩
    String queryParam = "?query=" + encodedQuery;

    URL url = new URL("https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode" + queryParam);
    HttpURLConnection con = (HttpURLConnection)url.openConnection();

    // 요청 헤더
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", clientId);
    con.setRequestProperty("X-NCP-APIGW-API-KEY", clientSecret);

    // Method 타입을 정의하고 API를 전송
    con.setRequestMethod("GET");

    BufferedReader br = null;

    int responseCode = con.getResponseCode();
    if(responseCode == 200) { // 정상 호출
      br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    } else {  // 오류 발생
      System.out.println("error!!!!!!! responseCode= " + responseCode);
      br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }
    String inputLine;

    if(br != null) {
      response = new StringBuffer();
      while ((inputLine = br.readLine()) != null) {
        response.append(inputLine);
      }
      br.close();

      // 결과 출력
      System.out.println(response.toString());
    } else {
      System.out.println("error !!!");
    }
  } catch (Exception e) {
    System.out.println(e);
  }
  System.out.println(response);

  return response.toString();
}




Reference

Rest API 요청 언어별 정리 - https://blog.muabow.com/291
https://digitalbourgeois.tistory.com/57

profile
🦋개발 공부 기록🦋

0개의 댓글