簡體   English   中英

如何在Android中等待khttp(kotlin)響應

[英]How to wait for khttp (kotlin) response in Android

我一直在嘗試使用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(),但這會使應用程序崩潰。 應該如何解決?

嘗試下一個代碼:

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM