【问题标题】:Why get request http dont working in Kotlin?为什么请求 http 在 Kotlin 中不起作用?
【发布时间】:2020-09-19 04:58:29
【问题描述】:

大家好,如果我在 emulator chrome 上写“http://10.0.1.42:8080/state”(这是我的 ip)这个工作,我在获取 http 请求时遇到问题,但是如果我想关闭 http 请求应用程序。有人可以帮我吗?

import android.content.Intent
import android.os.Bundle
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import kotlinx.coroutines.runBlocking
import java.util.*

class kmnActivity : AppCompatActivity() {
    val EXTRA_TEXT = "com.example.application.example.EXTRA_TEXT"
    var uuid = UUID.randomUUID().toString()
    var response = "nothing"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kmn)

        val textView = findViewById<TextView>(R.id.textView3)

        val kamenButton = findViewById<ImageButton>(R.id.kamen)
        val papierButton = findViewById<ImageButton>(R.id.papier)
        val nozniceButton = findViewById<ImageButton>(R.id.noznice)

        kamenButton.setOnClickListener {
            get_state()
            textView.setText(response)
           // openRollActivity()
        }

        papierButton.setOnClickListener {
            openRollActivity()
        }

        nozniceButton.setOnClickListener {
            openRollActivity()
        }
    }

    fun get_state(){
        val client = HttpClient()

        runBlocking {
             response = client.get<String>("http://10.0.1.42:8080/state") //Here not working
        }

        client.close()
    }

    fun openRollActivity() {
        val intent = Intent(this@kmnActivity, rollActivity::class.java)
        intent.putExtra("id", uuid)
        startActivity(intent)
    }
}

或者如果有人有更好的方法,他可以说我。感谢您的帮助。

【问题讨论】:

    标签: android-studio kotlin kotlin-coroutines ktor


    【解决方案1】:

    android:usesCleartextTraffic="true" 添加此代码 AndroidManifest.xml 文件 可以参考这个https://medium.com/@son.rommer/fix-cleartext-traffic-error-in-android-9-pie-2f4e9e2235e6你会明白的

    另一个可能的解决方法是 代替 HTTP 可以使用 https

    【讨论】:

      猜你喜欢
      • 2018-09-20
      • 1970-01-01
      • 2020-11-15
      • 2021-02-16
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      相关资源
      最近更新 更多