【问题标题】:Does Android (Java) have any function similar to file_get_contents($url) from PHP?Android(Java)是否有任何类似于 PHP 的 file_get_contents($url) 的功能?
【发布时间】:2021-11-23 13:37:00
【问题描述】:

我在我的 PHP 网页上使用 file_get_contents('https://example.com') 从静态网页获取数据。它工作得很好——现在我想在 Java 中做同样的事情,但我不知道这种函数在 Java 中是否可用......

我知道这听起来像是一个简单的问题,但我无法为我的应用找到可行的解决方案。你能指导我吗?谢谢!


编辑:我已经看到了引用存储中特定文件的解决方案,在尝试之后,它对我不起作用,我不知道为什么。我希望从正确的 URL(如https://mywebsite.com/data.php)读取内容。

【问题讨论】:

    标签: java android file-get-contents


    【解决方案1】:

    您可以使用 java.net 包中的 URL 类。

    创建 URL 对象的最简单方法是从包含人类可读形式的 URL 地址的字符串开始。

    URL url = new URL("https://mywebsite.com/data.php");

    您可以通过在其中一个 Util 类中创建以下方法来读取 URL 的内容。

    `

    静态字符串 getContents(字符串链接) {

        String out = "";
        try {
            URL url = new URL(link);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(url.openStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                out += line;
            }
            reader.close();
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return out;
    }
    

    `

    【讨论】:

    • out += line + "\n";最好使用 StringBuider。
    猜你喜欢
    • 2016-08-08
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 2023-03-31
    相关资源
    最近更新 更多