Home > Back-end >  Android Studio Retrieve file from URL and parse contents
Android Studio Retrieve file from URL and parse contents

Time:10-15

I cannot for the life of me how to figure out the most simple task of retrieving a text file from a url and reading its contents. All the code I find is 5-12 years old and doesn't work. Since android api 30 any network request on main thread give a android.os.NetworkOnMainThreadException. I'm stuck using kotlin for this portion.

I cant use DownloadManager (unless there is a way to store the file temporarily and retrieve contents) as the file doesnt need to be downloaded to the local storage only read. The closest ive seen is from: Android - How can I read a text file from a url?

try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.txt");

// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
    // str is one line of text; readLine() strips the newline character(s)
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

But this code doesn't work.

CodePudding user response:

So after 3 days of wanting to jump off a cliff. I found the answer. Of course it was a few minutes after asking the question here (first question ever so be kind.). The only Issue is you need a SSL cert for HTTPS on the server retrieving the file. My server is http but i can get a cert in there and fix that. to Test i threw up a github repository and linked to the raw text file. Here is my solution if this saves you 3 days pour one out for me.

Thread {
            try {
                val url = URL("https://raw.githubusercontent.com/USERNAME/NeedHTTPSdontWanaSSL/main/info.txt")
                val uc: HttpsURLConnection = url.openConnection() as HttpsURLConnection
                val br = BufferedReader(InputStreamReader(uc.getInputStream()))
                var line: String?
                val lin2 = StringBuilder()
                while (br.readLine().also { line = it } != null) {
                    lin2.append(line)
                }
                Log.d("The Text", "$lin2")
            } catch (e: IOException) {
                Log.d("texts", "onClick: "   e.getLocalizedMessage())
                e.printStackTrace()
            }
        }.start()

Credit: answered Aug 12, 2018 at 9:29 Aishik kirtaniya Android - How can I read a text file from a url?

  • Related