Spring
API
HTTP / WEB 통신

HTTP 연결

Http URL Connection

Http URL Connection은 다음과 같은 절차를 따른다.

  1. URL 객체 생성
  2. 연결 초기화
  3. HTTP 메서드 설정
  4. 요청 헤더 설정(욥션)
  5. 요청 본문 작성(옵션)
  6. 서버 응답 확인
  7. 응답 헤더 읽기(옵션)
  8. 응답 본문 읽기
  9. 연결 종료

예제

public static void main(String[] args) {
    String apiKey = JsonAPIKey;
    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();
        // Get 방식으로 호출
        connection.setRequestMethod("GET");
        // Json 방식으로 받겠다
        connection.setRequestProperty("Accept", "application/json");
        // Response Code
        int responseCode = connection.getResponseCode(); // 200
        if (responseCode == 200) {
            // 스트림의 연결
            // Reader : 문자 단위로 읽을 수 있게 해준다 (한글 인코딩 문제)
            // Buffered Reader : 데이터를 모아서 한 번에 처리하기 위해서 사용
            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();
            // Json Data 중에서 main에 해당하는 부분을 Json Data로 변환
            // 해당하는 데이터에서 temp 부분을 getAsDouble 즉, double 형태로 가져옴
            double temp = weatherData.getAsJsonObject("main").get("temp").getAsDouble();
            System.out.println("temp : " + temp);
            connection.disconnect();
        } else {
 
        }
    } catch (Exception e) {
 
    }
}

Jsoup(크롤링)

Jsoup (opens in a new tab)은 웹 크롤링, 웹 스크레이핑, 데이터 추출 등의 작업을 수행할 수 있는 Java 라이브러리이다.

public static void main(String[] args) throws IOException {
    String url = "https://sum.su.or.kr:8888/bible/today";
    Document document = (Document) Jsoup.connect(url).get();
 
    // id가 bible_text, bibleinfo_box에 해당하는 tag
    Element bibleText = document.getElementById("bible_text");
    Element bibleInfoBox = document.getElementById("bibleinfo_box");
 
    System.out.println("Bible Text " + bibleText.text());
    System.out.println("Bible Info Box " + bibleInfoBox.text());
    System.out.println();
 
    // JavaScript의 클래스임
    // num과 info의 class에 해당되는 Element들이 전부 들어오게 됨
    Elements numElements = document.select(".num"); // num class
    Elements infoElements = document.select(".info"); // info class
 
    for (int i = 0; i < numElements.size() ; i++) {
        System.out.println(numElements.get(i).text() + " : " + infoElements.get(i).text());
    }
}