Class java.net.URL đại diện cho Uniform Resource Locator. Dùng openStream() để lấy InputStream đọc dữ liệu từ web.
Các bước đọc dữ liệu từ URL
- Tạo object
URLtừ string URL. - Gọi
openStream()lấyInputStream. - Bọc trong
ScannerhoặcBufferedReaderđể đọc tiện lợi. - Xử lý dữ liệu (parse HTML, JSON, v.v.).
Ví dụ đọc trang web
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class ReadWebPage {
public static void main(String args[]) throws IOException {
URL url = new URL("https://www.example.com/");
Scanner sc = new Scanner(url.openStream());
StringBuilder sb = new StringBuilder();
while (sc.hasNext()) {
sb.append(sc.next());
}
String result = sb.toString();
System.out.println("Raw HTML: " + result);
// Loại bỏ HTML tags đơn giản
String textOnly = result.replaceAll("<[^>]*>", "");
System.out.println("Text only: " + textOnly);
}
}
Kết quả mẫu
<html><body><h1>It works!</h1></body></html> Text only: It works!
Mở rộng: Ghi dữ liệu (POST) - Dùng HttpURLConnection
URL url = new URL("https://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
String jsonInput = "{\"name\":\"John\"}";
try (var os = conn.getOutputStream()) {
os.write(jsonInput.getBytes());
}
int responseCode = conn.getResponseCode();
try (var is = conn.getInputStream(); var reader = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
Hiện nay: Thường dùng thư viện cao cấp hơn: HttpClient (Java 11+), OkHttp, Retrofit, WebClient (Spring).