Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 외부 라이브러리를 사용하지 않고 웹 페이지의 내용을 읽는 방법은 무엇입니까?

<시간/>

URL java.net 패키지의 클래스는 월드 와이드 웹에서 리소스(파일 또는 디렉토리 또는 참조)를 가리키는 데 사용되는 Uniform Resource Locator를 나타냅니다.

openStream() 이 클래스의 메서드는 현재 개체가 나타내는 URL에 대한 연결을 열고 URL에서 데이터를 읽을 수 있는 InputStream 개체를 반환합니다.

따라서 웹 페이지에서 데이터를 읽으려면(URL 클래스 사용) -

  • 원하는 웹 페이지의 URL을 생성자에 매개변수로 전달하여 java.net.URL 클래스를 인스턴스화합니다.

  • openStream() 메서드를 호출하고 InputStream 객체를 검색합니다.

  • 위에서 검색한 InputStream 객체를 매개변수로 전달하여 Scanner 클래스를 인스턴스화합니다.

import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class ReadingWebPage {
   public static void main(String args[]) throws IOException {
      //Instantiating the URL class
      URL url = new URL("https://www.something.com/");
      //Retrieving the contents of the specified page
      Scanner sc = new Scanner(url.openStream());
      //Instantiating the StringBuffer class to hold the result
      StringBuffer sb = new StringBuffer();
      while(sc.hasNext()) {
         sb.append(sc.next());
         //System.out.println(sc.next());
      }
      //Retrieving the String from the String Buffer object
      String result = sb.toString();
      System.out.println(result);
      //Removing the HTML tags
      result = result.replaceAll("<[^>]*>", "");
      System.out.println("Contents of the web page: "+result);
   }
}

출력

<html><body><h1>Itworks!</h1></body></html>
Contents of the web page: Itworks!