如何在Android中等待khttp(kotlin)响应

时间:2018-11-27 17:47:10

标签: android http kotlin

我一直在尝试使用khttp在android活动中发送.jpg文件,但无法使其正常工作。

fun sendImage(view: View) {

    try {
        var bmp = (imageView?.drawable as BitmapDrawable).bitmap
        var bos = ByteArrayOutputStream()
        bmp.compress(Bitmap.CompressFormat.JPEG, 0, bos)
        var response: Response? = null
        findViewById<TextView>(R.id.image_desc).text = "Connecting to " + SERVER_URL;

        try {
            val job=GlobalScope.launch {
                response = post(SERVER_URL, files = listOf(File(path).fileLike(name = "Image.jpg")))
            }

            findViewById<TextView>(R.id.image_desc).text = "Image contains: ${response?.text}"
        } catch (e: Exception) {
            findViewById<TextView>(R.id.image_desc).text = "Connection failed - please check fields are valid"
            findViewById<TextView>(R.id.image_desc).text = e.toString()
        }

    } catch (e: UnknownHostException) {
        findViewById<TextView>(R.id.image_desc).text = "Unknown host :("
        e.printStackTrace()
    } catch (e: IOException) {
        findViewById<TextView>(R.id.image_desc).text = "IO exceptiion :("
        e.printStackTrace()
    } catch (e: Exception) {
        findViewById<TextView>(R.id.image_desc).text = "Other exception :("
        e.printStackTrace()
    }
}

我发送图像后,image_desc textView的文本更改为Image包含:null。我确定服务器不是问题,因为当我使用以下python代码对其进行测试时:

import requests

url=...
files = {'file': open('./test/cat.jpg', 'rb')}
r=requests.post(url,files=files)
print (r.text)

经过短暂的延迟,我得到了期望的响应。我尝试过将sendImage变成一个暂停函数并编写job.join(),但这会使应用程序崩溃。应该如何解决?

1 个答案:

答案 0 :(得分:1)

尝试下一个代码:

val job = GlobalScope.launch(Dispatchers.Main) {
    val postOperation = async(Dispatchers.IO) { // <- extension on launch scope, launched in IO dispatcher
        // blocking I/O operation
        post(SERVER_URL, files = listOf(File(path).fileLike(name = "Image.jpg")))
    }
    response = postOperation.await() // wait for result of I/O operation without blocking the main thread
    findViewById<TextView>(R.id.image_desc).text = "Image contains: ${response?.text}"
}

还向应用程序的build.gradle依赖项添加下一行:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1'