IOException:AsyncTask图像下载Kotlin Android(坏文件描述符)

UPDATE

经过一些调试后,我发现在给定代码中的Catch块得到执行,没有任何异常异常。 我打印inputstream返回一些值,事件位图varibale被初始化,但一旦它执行catch块,它返回null onPostExecute方法。

找出为什么发生?

请查看studio的调试截图

结束

我正在使用Android Studio 3.0。

使用Kotlin支持创建简单的Android应用程序,该应用程序通过AsyncTask类和HTTPURLConnection类从http协议网址下载图像。

在执行AsyncTask类时,我从HTTPURLConnection对象获取http响应代码200,但是使用BitmapFactory.decodeStream(inputstream)方法解码流时将引发IOEXception。

StackTrace倾向于错误引起:android.system.ErrnoException:recvfrom失败:EBADF,在调用此BitmapFactory.decodeStream(inputstream)方法的同一行上。

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 } 

您已经阅读了回应主体后,应该只调用断开连接。

这是Java,但你可以适应Kotlin:

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