如何在Android Studio中将网站内容转换为字符串?

时间:2018-10-26 12:03:57

标签: java

我想在我的应用程序中显示网站内容的一部分。我在这里看到了一些解决方案,但是它们都非常老,不能与更新版本的Android Studio一起使用。所以也许有人可以帮忙。

2 个答案:

答案 0 :(得分:0)

https://jsoup.org/应该有助于获取完整的站点数据,并根据类,id等进行解析。例如,下面的代码获取并打印站点的标题:

Document doc = Jsoup.connect("http://www.moodmusic.today/").get();
String title = doc.select("title").text();
System.out.println(title);

答案 1 :(得分:0)

如果要从目标网站获取原始数据,则需要执行以下操作:

  • 使用参数中指定的网站链接创建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.MalformedURLExceptionjava.io.IOException

要将InputStream转换为字符串

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,一切顺利!

希望这会有所帮助!