2 回答
TA贡献1831条经验 获得超9个赞
https://jsoup.org/应该有助于获取完整的站点数据,根据类、ID 等对其进行解析。例如,下面的代码获取并打印站点的标题:
Document doc = Jsoup.connect("http://www.moodmusic.today/").get();
String title = doc.select("title").text();
System.out.println(title);
TA贡献1934条经验 获得超2个赞
如果您想从目标网站获取原始数据,您需要执行以下操作:
使用参数中指定的网站链接创建一个 URL 对象
将其投射到 HttpURLConnection
检索其 InputStream
将其转换为字符串
无论您使用哪种 IDE,这通常都适用于 java。
要检索连接的 InputStream:
// Create a URL object
URL url = new URL("https://yourwebsitehere.domain");
// Retrieve its input stream
HttpURLConnection connection = ((HttpURLConnection) url.openConnection());
InputStream instream = connection.getInputStream();
确保处理java.net.MalformedURLException和java.io.IOException
将 InputStream 转换为 String
public static String toString(InputStream in) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
reader.close();
return builder.toString();
}
您可以复制和修改上面的代码并在您的源代码中使用它!
确保有以下导入
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
例子:
public static String getDataRaw() throws IOException, MalformedURLException {
URL url = new URL("https://yourwebsitehere.domain");
HttpURLConnection connection = ((HttpURLConnection) url.openConnection());
InputStream instream = connection.getInputStream();
return toString(instream);
}
要调用 getDataRaw(),处理 IOException 和 MalformedURLException,您就可以开始了!
希望这可以帮助!
添加回答
举报
