1
votes

UPDATE

After some debugging, I find out that Catch block in given code get executed without any exception exception. I print inputstream which return some value, event bitmap varibale gets initialised but once it executed catch block, it return null to onPostExecute method.

Searching out why it is happening ?

Please check debug screenshot of studio

END

I am using Android Studio 3.0.

Created simple android application with Kotlin Support, which download image from give http protocol url with help of AsyncTask class and HTTPURLConnection class.

On execution of AsyncTask class, I am getting http response code 200 from HTTPURLConnection object but while decoding stream with BitmapFactory.decodeStream(inputstream) method throws IOEXception.

StackTrace tends to error Caused by: android.system.ErrnoException: recvfrom failed: EBADF , on same line where calling this BitmapFactory.decodeStream(inputstream) method.

    override fun doInBackground(vararg args: String?): Bitmap? {

    var bitmap: Bitmap? = null

    try {

        val url = URL(args[0])
        val connection: HttpURLConnection = url.openConnection() as HttpURLConnection

        connection.requestMethod = "GET"
        connection.connectTimeout = 10 * 60 * 60
        connection.readTimeout = 10 * 60 * 60
        connection.doInput = true
        connection.doOutput = true

        connection.connect()
        val responseCode = connection.responseCode
        if (HTTP_OK == responseCode) {
            if (null != connection.inputStream) {
                val inputStream = connection.inputStream
                connection.disconnect()
                bitmap = BitmapFactory.decodeStream(inputStream)
            }
        }else{
            Log.e("####","Error Response Code: ${responseCode}")
        }

    } catch (ex: IOException) {
        Log.e("####",ex.localizedMessage)

    } catch (ex: MalformedURLException) {
        ex.printStackTrace()

    } catch (ex: Exception) {
        ex.printStackTrace()

    }

    return bitmap
}
2
connection.disconnect() I would not do that if i wanted to read from the stream yet.greenapps
I have already collected inputstream reference : before disconnect line but even after removing connection.disconnect() still i am getting same error.Ganesh Tikone
connection.doOutput = true Remove that statement. It´s for POST.greenapps
@geenapps: still same issueGanesh Tikone

2 Answers

1
votes

You should only call disconnect after you already read response body.

1
votes

It's java, but you can adapt it to Kotlin:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
connection.disconnect()