【发布时间】: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