猿问
如何在 Android Studio 中将网站的内容转换为字符串?
我想在我的应用程序中显示网站内容的一部分。我在这里看到了一些解决方案,但它们都非常旧,并且不适用于较新版本的 Android Studio。所以也许有人可以帮忙。
心有法竹
浏览 204
回答 2
2回答
天涯尽头无女友
https://jsoup.org/应该有助于获取完整的站点数据,根据类、ID 等对其进行解析。例如,下面的代码获取并打印站点的标题:Document doc = Jsoup.connect("http://www.moodmusic.today/").get();String title = doc.select("title").text();System.out.println(title);
0
0
0
撒科打诨
如果您想从目标网站获取原始数据,您需要执行以下操作:使用参数中指定的网站链接创建一个 URL 对象将其投射到 HttpURLConnection检索其 InputStream将其转换为字符串无论您使用哪种 IDE,这通常都适用于 java。要检索连接的 InputStream:// Create a URL objectURL url = new URL("https://yourwebsitehere.domain");// Retrieve its input streamHttpURLConnection connection = ((HttpURLConnection) url.openConnection());InputStream instream = connection.getInputStream();确保处理java.net.MalformedURLException和java.io.IOException将 InputStream 转换为 Stringpublic 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,您就可以开始了!希望这可以帮助!
0
0
0
随时随地看视频
慕课网APP
相关分类
Java
我要回答