共計 944 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中,可以使用 java.net 包中的 URLConnection 和 InputStream 來通過 URL 獲取數(shù)據(jù)。以下是一個簡單的示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class URLDataFetcher {public static void main(String[] args) {try {// 創(chuàng)建 URL 對象
URL url = new URL("https://www.example.com");
// 打開連接
URLConnection connection = url.openConnection();
// 獲取輸入流
InputStream inputStream = connection.getInputStream();
// 創(chuàng)建一個 BufferedReader 來讀取數(shù)據(jù)
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder data = new StringBuilder();
while ((line = reader.readLine()) != null) {data.append(line);
}
// 關(guān)閉資源
reader.close();
inputStream.close();
// 輸出獲取到的數(shù)據(jù)
System.out.println(data.toString());
} catch (IOException e) {e.printStackTrace();
}
}
}
在該示例中,首先創(chuàng)建了一個 URL 對象,然后通過 URL 對象打開連接。接下來,通過 URLConnection 對象獲取輸入流,并使用 BufferedReader 來讀取數(shù)據(jù)。最后,關(guān)閉資源并輸出獲取到的數(shù)據(jù)。
請?zhí)鎿Q https://www.example.com
為你要獲取數(shù)據(jù)的 URL。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完
發(fā)表至: Java
2023-12-12