【问题标题】:NetworkOnMainThreadException even after subscribing to schedulers.io()NetworkOnMainThreadException 即使订阅了 schedulers.io()
【发布时间】:2019-08-15 20:16:58
【问题描述】:

我尝试练习我的技能,并尝试使用 RX java 模拟网络。

但是当我尝试执行我的代码时,我得到了NetworkOnMainThreadException,尽管我使用了Schedulers.io() 线程。

我想将代码分成三个方法,但它不起作用。我已经用.fromCallable{} 替换了所有.just(),但它仍然无法正常工作

这是我的代码:

fun String.post(authorization: String, params: HashMap<String, String>): Single<out Response> {
    try {
        val url = URL(this)
        val connection = url.openConnection() as HttpsURLConnection
        connection.apply {
            requestMethod = "POST"
            addRequestProperty("Authorization", authorization.sha1())
            addRequestProperty("Content-Type", "application/x-www-form-urlencoded")
            doOutput = true
            DataOutputStream(connection.outputStream).use {
                it.write(params.toUrlEncoded().toByteArray())
            }

            val single = when (connection.responseCode) {
                200, 201 -> {
                    val body = connection.inputStream.bufferedReader().use(BufferedReader::readText)
                    Single.fromCallable { DataResponse(HttpsURLConnection.HTTP_OK, body) }
                }
                else -> {
                    val message = connection.errorStream.bufferedReader().use(BufferedReader::readText)
                    Single.fromCallable { ErrorResponse(connection.responseCode, message) }
                }
            }
            connection.disconnect()
            return single
        }
    } catch (e: Exception) {
        e.printStackTrace()
        return Single.fromCallable { ErrorResponse(500, e.message.toString()) }
    }
} 

fun downloadImage(authorization: String, params: HashMap<String, String>): Single<Any> {
        return (BuildConfig.BASE_URL + IMAGE_URL).post(authorization, params).flatMap {
            when (it) {
                is DataResponse -> {
                    val json = JSONObject(it.body)
                    if (json.has("image")) {
                        return@flatMap Single.fromCallable { ImageData(json.getString("image")) }
                    } else {
                        return@flatMap Single.error<HttpException>(HttpException(-1, ""))
                    }
                }
                is ErrorResponse -> {
                    return@flatMap Single.error<HttpException>(HttpException(it.code, it.message))
                }
                else -> {
                    return@flatMap Single.error<HttpException>(HttpException(-1, ""))
                }
            }
        }
    } 

repository.downloadImage(password, hashMapOf("username" to login)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribeBy({
                it.printStackTrace()
            }, {
                _imageData.postValue(it as ImageData)
            }) 

【问题讨论】:

    标签: android kotlin rx-java2 kotlin-android-extensions


    【解决方案1】:

    好的,这很奇怪,但我设法通过从 String.post() 函数中删除 Single() 包装类来解决它。所以工作代码:

    fun String.post(authorization: String, params: HashMap<String, String>): Response {
        try {
            val url = URL(this)
            val connection = url.openConnection() as HttpsURLConnection
            connection.apply {
                requestMethod = "POST"
                addRequestProperty("Authorization", authorization.sha1())
                addRequestProperty("Content-Type", "application/x-www-form-urlencoded")
                doOutput = true
                DataOutputStream(connection.outputStream).use {
                    it.write(params.toUrlEncoded().toByteArray())
                }
    
                val response = when (connection.responseCode) {
                    200, 201 -> {
                        val body = connection.inputStream.bufferedReader().use(BufferedReader::readText)
                        DataResponse(HttpsURLConnection.HTTP_OK, body)
                    }
                    else -> {
                        val message = connection.errorStream.bufferedReader().use(BufferedReader::readText)
                         ErrorResponse(connection.responseCode, message)
                    }
                }
                connection.disconnect()
                return response
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return ErrorResponse(500, e.message.toString())
        }
    } 
    
    
    fun downloadImage(authorization: String, params: HashMap<String, String>): Single<Any> {
            return Single.fromCallable { (BuildConfig.BASE_URL + IMAGE_URL).post(authorization, params) }.flatMap {
                when (it) {
                    is DataResponse -> {
                        val json = JSONObject(it.body)
                        if (json.has("image")) {
                            return@flatMap Single.fromCallable { ImageData(json.getString("image")) }
                        } else {
                            return@flatMap Single.error<HttpException>(HttpException(-1, ""))
                        }
                    }
                    is ErrorResponse -> {
                        return@flatMap Single.error<HttpException>(HttpException(it.code, it.message))
                    }
                    else -> {
                        return@flatMap Single.error<HttpException>(HttpException(-1, ""))
                    }
                }
            }
        } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-24
      • 2021-03-25
      • 2016-12-11
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多