반응형

Java를 사용하여 특정 웹사이트의 URL에서 HTML을 가져와 렌더링하려면, 다음과 같은 단계를 따를 수 있습니다:


1. Java에서 HTML 가져오기

Java에서는 HTTP 요청을 통해 특정 URL의 HTML 데이터를 가져올 수 있습니다. 이를 위해 HttpURLConnection이나 Apache HttpClient, Jsoup 라이브러리를 사용할 수 있습니다.

HttpURLConnection 예제 (Java 기본 API)

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

public class FetchHtml {
    public static void main(String[] args) {
        String url = "https://example.com"; // HTML을 가져올 URL
        try {
            URL targetUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder htmlContent = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    htmlContent.append(inputLine).append("\n");
                }
                in.close();

                // HTML 출력
                System.out.println(htmlContent.toString());
            } else {
                System.out.println("Failed to fetch HTML. HTTP Response Code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Jsoup 예제 (외부 라이브러리 사용)

Jsoup은 HTML 처리에 특화된 Java 라이브러리입니다. HTML 파싱과 DOM 조작을 쉽게 할 수 있습니다.

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class FetchHtmlWithJsoup {
    public static void main(String[] args) {
        String url = "https://example.com"; // HTML을 가져올 URL
        try {
            Document doc = Jsoup.connect(url).get();
            System.out.println(doc.html()); // HTML 출력
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. 가져온 HTML을 웹 브라우저에 표시하기

HTML 데이터를 가져온 후, 이를 클라이언트로 반환하려면 Spring Boot와 같은 Java 웹 프레임워크를 사용할 수 있습니다.

Spring Boot 사용

  1. HTML 데이터를 반환하는 컨트롤러:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HtmlController {

    @GetMapping("/fetch-html")
    public String fetchHtml() {
        String url = "https://example.com"; // HTML을 가져올 URL
        try {
            Document doc = Jsoup.connect(url).get();
            return doc.html(); // HTML 반환
        } catch (Exception e) {
            e.printStackTrace();
            return "Error fetching HTML.";
        }
    }
}
  1. HTML을 클라이언트에서 표시:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Viewer</title>
</head>
<body>
    <h1>Fetched HTML Content</h1>
    <div id="content"></div>

    <script>
        fetch('/fetch-html')
            .then(response => response.text())
            .then(html => {
                document.getElementById('content').innerHTML = html;
            })
            .catch(error => {
                console.error('Error fetching HTML:', error);
            });
    </script>
</body>
</html>

3. CORS와 보안 문제 해결

  • CORS 정책: 클라이언트가 다른 도메인에서 데이터를 가져올 때 CORS 정책 문제가 발생할 수 있습니다. 서버에서 @CrossOrigin 또는 적절한 HTTP 헤더를 설정해야 합니다.
  • User-Agent 설정: 특정 사이트는 요청의 User-Agent 헤더가 설정되지 않으면 요청을 차단할 수 있으므로 HttpURLConnection 또는 Jsoup에서 User-Agent를 지정해야 합니다.

4. 전체 코드 통합 (Spring Boot)

Spring Boot 애플리케이션으로 HTML을 가져오고 클라이언트에 표시하는 전체 예제:

Spring Boot Controller

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin // CORS 허용
public class HtmlController {

    @GetMapping("/fetch-html")
    public String fetchHtml() {
        String url = "https://example.com"; // 가져올 URL
        try {
            Document doc = Jsoup.connect(url).get();
            return doc.html(); // HTML 반환
        } catch (Exception e) {
            e.printStackTrace();
            return "Error fetching HTML.";
        }
    }
}

HTML 클라이언트

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Viewer</title>
</head>
<body>
    <h1>Fetched HTML Content</h1>
    <div id="content"></div>

    <script>
        fetch('/fetch-html')
            .then(response => response.text())
            .then(html => {
                document.getElementById('content').innerHTML = html;
            })
            .catch(error => {
                console.error('Error fetching HTML:', error);
            });
    </script>
</body>
</html>

결론

  • Java로 특정 URL의 HTML을 가져오려면 HttpURLConnection 또는 Jsoup을 사용합니다.
  • 가져온 HTML은 Spring Boot와 같은 웹 프레임워크로 클라이언트에 반환할 수 있습니다.
  • HTML 데이터를 표시할 때는 클라이언트에서 fetch API를 사용하거나 <iframe> 태그로 바로 렌더링할 수 있습니다.
반응형

+ Recent posts