ใช้คลาส java.net.URL และ openStream() เพื่ออ่านข้อมูลจาก Web Resource อย่างง่าย
ขั้นตอนหลัก (Read)
- สร้าง
URLObject ด้วย String URL - เรียก
url.openStream()ได้InputStream - ห่อด้วย
Scanner,BufferedReader, หรือInputStreamReaderเพื่ออ่านข้อมูล
ตัวอย่าง: อ่านหน้าเว็บด้วย Scanner
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class ReadWebPage {
public static void main(String[] args) throws IOException {
// 1. สร้าง URL
URL url = new URL("https://example.com/");
// 2. เปิด Stream + 3. อ่านด้วย Scanner
try (Scanner sc = new Scanner(url.openStream())) {
StringBuilder sb = new StringBuilder();
while (sc.hasNext()) {
sb.append(sc.next()).append(" ");
}
String content = sb.toString();
// ลบ HTML Tags (Simple)
String textOnly = content.replaceAll("<[^>]*>", "");
System.out.println("Content: " + textOnly);
}
}
}
ตัวอย่าง: ใช้ BufferedReader (มีประสิทธิภาพมากกว่า)
import java.io.*;
import java.net.URL;
public class ReadWithBufferedReader {
public static void main(String[] args) throws IOException {
URL url = new URL("https://example.com/");
try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
}
ขั้นตอนสำหรับ Write (HTTP POST/PUT)
URL class ใช้สำหรับ Read เท่านั้น สำหรับ Write ต้องใช้ HttpURLConnection
import java.io.*;
import java.net.*;
public class WriteToUrl {
public static void main(String[] args) throws IOException {
URL url = new URL("https://httpbin.org/post");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Config สำหรับ POST
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
// เขียน Request Body
String json = "{\"name\":\"John\",\"age\":30}";
try (OutputStream os = conn.getOutputStream()) {
os.write(json.getBytes("UTF-8"));
}
// อ่าน Response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
}
สรุป
| Operation | Class/Method |
|---|---|
| Simple GET Read | URL.openStream() + Scanner/BufferedReader |
| Advanced HTTP (POST, Headers, Timeout) | HttpURLConnection หรือ HttpClient (Java 11+) |
Java 11+ แนะนำใช้ java.net.http.HttpClient (Modern, Async, Reactive)