Home > OS >  Issues with GET request on Android Studio
Issues with GET request on Android Studio

Time:10-10

I'm trying to create a simple GET request on Android Studio using an AsyncTask, as shown in the code snippet below. When debugging, I notice that when I do url.openConnection(), the HttpURLConnection has a responseCode of -1. I've looked all over to see what is the issue, and I still can't figure it out. When I tried a GET request on Visual Studio, I was able to get the response correctly.

Here is the main code for my AsyncTask:

override fun doInBackground(vararg params: Any): String {
            var result: String
            var connection: HttpURLConnection? = null
            try {
                val url = URL(myMockURLstring)
                connection = url.openConnection() as HttpURLConnection // *** messes up here ***
                connection.doOutput = true
                connection.doInput = true
                connection.instanceFollowRedirects = false
                connection.requestMethod = "GET"
                connection.setRequestProperty("Content-Type", "application/json")
                connection.setRequestProperty("charset", "utf-8")
                connection.setRequestProperty("Accept", "application/json")
                connection.useCaches = false
                val httpResult: Int = connection.responseCode // Gets the status code from an HTTP response message.

                if (httpResult == HttpURLConnection.HTTP_OK) {
                    //inputstreamreader code
                    
                } else {
                    result = connection.responseMessage
                }

            } catch (e: SocketTimeoutException) {
                result = "Connection Timeout"
            } catch (e: Exception) {
                result = "Error : "   e.message
            } finally {
                connection?.disconnect()
            }

            return result
        }

I also have the following two lines in my Manifest file:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

Any idea what I should add or change to get it to work on Android Studio?

EDIT: Changed to GET

CodePudding user response:

Have you tried to declare connection as this?

val url = URL(myMockURLstring)
val connection = url.openConnection() as HttpURLConnection

Then you can test the return of this URL before start to do anything else:

if (connection.responseCode == HttpURLConnection.HTTP_OK) {
    try {
        // DO YOUR STUFF HERE
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        connection.disconnect()
    }
} else {
    println("ERROR ${connection.responseCode}")
}

Try setting your connection.doOutput = false too, like @blackapps said.

Also, it might be a better option to use Kotlin Coroutines, a more modern way to deal with async tasks.

  • Related