Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีอ่านเนื้อหาเว็บเพจเก็บไว้ใน String ใน Java

มีหลายวิธีอ่านเนื้อหาเว็บเพจใน Java นี่คือ 3 วิธีหลัก:

วิธีที่ 1: ใช้ URL.openStream() (Built-in, ไม่ต้อง library)

ใช้ java.net.URL และ Scanner หรือ BufferedReader


import java.io.IOException;
import java.net.URL;
import java.util.Scanner;

public class ReadWebPageURL {
    public static void main(String[] args) throws IOException {
        URL url = new URL("https://www.example.com/");
        try (Scanner sc = new Scanner(url.openStream(), "UTF-8")) {
            StringBuilder sb = new StringBuilder();
            while (sc.hasNextLine()) {
                sb.append(sc.nextLine()).append("\n");
            }
            String html = sb.toString();
            System.out.println("HTML length: " + html.length());
            
            // Strip HTML tags (simple)
            String text = html.replaceAll("<[^>]*>", "");
            System.out.println("Text only: " + text);
        }
    }
}

วิธีที่ 2: ใช้ Apache HttpClient (External Library)

HttpClient รองรับ HTTP/1.1, HTTP/2, connection pooling, redirect, authentication

Dependency (Maven)


<dependency>
  <groupId>org.apache.httpcomponents.client5</groupId>
  <artifactId>httpclient5</artifactId>
  <version>5.2.1</version>
</dependency>

ตัวอย่าง


import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core.http.io.entity.EntityUtils;

public class ReadWebPageHttpClient {
    public static void main(String[] args) throws Exception {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet request = new HttpGet("https://www.example.com/");
            try (var response = client.execute(request)) {
                String html = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("Status: " + response.getCode());
                System.out.println("HTML length: " + html.length());
            }
        }
    }
}

วิธีที่ 3: ใช้ Jsoup (HTML Parser Library)

Jsoup parse HTML ให้เป็น DOM tree สามารถ query ด้วย CSS selector ได้

Dependency


<dependency>
  <groupId>org.jsoup</groupId>
  <artifactId>jsoup</artifactId>
  <version>1.16.1</version>
</dependency>

ตัวอย่าง


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

public class ReadWebPageJsoup {
    public static void main(String[] args) throws IOException {
        Document doc = Jsoup.connect("https://www.example.com/").get();
        
        // เฉพาะข้อความ (ไม่มี tags)
        String text = doc.body().text();
        System.out.println("Text: " + text);
        
        // หรือ extract เฉพาะส่วนที่ต้องการ
        String title = doc.title();
        String h1 = doc.select("h1").text();
        System.out.println("Title: " + title);
        System.out.println("H1: " + h1);
    }
}

การเปรียบเทียบ

วิธีDependencyHTML ParsingRedirect/SSLเหมาะสำหรับ
URL.openStream()ไม่ต้องไม่มี (raw HTML)พื้นฐานSimple, ไม่ต้องเพิ่ม lib
HttpClientต้องไม่มี (raw HTML)เต็มรูปแบบProduction HTTP client
Jsoupต้องมี (DOM, CSS Selector)มีWeb scraping, extract data
Java 11 HttpClientBuilt-inไม่มีเต็มรูปแบบModern, async, HTTP/2

Java 11+ HttpClient (Built-in, Modern)


import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ReadWebPageJava11 {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://www.example.com/"))
            .build();
        
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("Status: " + response.statusCode());
        System.out.println("Body: " + response.body());
    }
}

ข้อควรระวัง

  • ตั้งค่า Timeout: url.openConnection().setConnectTimeout(5000)
  • User-Agent: บางเว็บบล็อก default Java user-agent
  • Encoding: ระบุ charset ชัดเจน (UTF-8)
  • Respect robots.txt และ rate limiting