androidandroid-networking

What is the proper way to do an HTTP GET on older versions of Android?


I've been having an issue making HTTP GET requests consistent between versions of Android. On Android 7-12, this code works perfectly for accessing my remote server, and gets a response back relatively quickly.

            executor.execute { //send an HTTP GET Request to the server, send out some mail babyyyyy
                try {
                    val geturl = URL(url)
                    var jsonstring = geturl.readText();
                    var obj:JSONObject = JSONObject(jsonstring)
                    success = obj.getBoolean("success")
                    println(jsonstring)

                } catch(e:Exception) {
                    success=false;
                    println(e)

                }

                handler.post { //clean up, we're done here

However, when I try to run the exact same code under android 6.01, for example, I get returned a FileNotFoundException. How am I to make requests on versions lower than 7.0, and am I even doing this right? Thanks.


Solution

  • Well, massive thanks to @talhatek to pointing me in the right direction, but OkHTTP Worked great! complete set in replacement for the code I had previously, and my app's now working on android 6.0. For anyone needing the code, here's how I reimplemented it.

                executor.execute { //send an HTTP GET Request to the server, send out some mail babyyyyy
                    try {
                        val client = OkHttpClient()
                        val request: Request = Request.Builder()
                            .url(url)
                            .build()
    
                        client.newCall(request).execute()
                            .use { response ->
                                //handle stuff
                            }
    
                    } catch(e:Exception) {
                        success=false;
                        println(e)
    
                    }