在某些应用中,我们可能需要从互联网下载网页并将其内容提取为字符串。一个流行的用例是网页抓取或内容解析。
在本教程中,我们将使用Jsoup和_HttpURLConnection_来下载一个示例网页。
使用_HttpURLConnection_下载网页
_HttpURLConnection_是_URLConnection_的一个子类。**它有助于连接到使用HTTP协议的统一资源定位符(URL)。**该类包含不同的方法来操作HTTP请求。
让我们使用_HttpURLConnection_下载一个示例网页:
@Test
void givenURLConnection_whenRetrieveWebpage_thenWebpageIsNotNullAndContainsHtmlTag() throws IOException {
URL url = new URL("https://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
StringBuilder responseBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseBuilder.append(line);
}
assertNotNull(responseBuilder);
assertTrue(responseBuilder.toString()
.contains("``<html>``"));
}
}
大约 2 分钟