Home > Back-end >  Does Android (Java) have any function similar to file_get_contents($url) from PHP?
Does Android (Java) have any function similar to file_get_contents($url) from PHP?

Time:10-02

I am using file_get_contents('https://example.com') on my PHP webpage, to get data from a static webpage. It works perfectly - and now I want to do the same in Java, but I don't know if this sort of function is available in Java or not...

I know it might sound like a simple question, but I am unable to find myself a feasible solution for my app. Can you guide me on this? Thanks!


Edit : I have seen solutions which refer to particular files in storage, and after trying them, it didn't work for me and I don't know why. I am looking to read contents from a proper URL (like https://mywebsite.com/data.php).

CodePudding user response:

You can use URL class in the java.net package.

The simplest approach to make a URL object is to start with a String that contains the URL address in human-readable form.

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

You can read contents of the URL by creating following method in one of your Util classes.

`

static String getContents(String link) {

    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;
}

`

  • Related