【问题标题】:Can't connect to a localhost from kotlin and can connect to an online api无法从 kotlin 连接到 localhost 并且可以连接到在线 api
【发布时间】:2019-11-16 18:20:04
【问题描述】:

所以我遇到了这个问题,我无法连接到我的本地主机,但我可以连接到在线主机,这是我的代码,我只是在调试器中执行请求失败

 fun fetchJson() {
    println("Attempting to Fetch JSON")

    val url = "http://192.168.1.***:8*/demo/mysql/selector.php"

    val request = Request.Builder().url(url).build()

    val client = OkHttpClient()
    client.newCall(request).enqueue(object: Callback {
        override fun onResponse(call: Call, response: Response) {
            val resulta=response.body()?.string();

            println(resulta)
            println("Sucees")

            val gson = GsonBuilder().create()

            val homeFeed = gson.fromJson(resulta, HomeFeed::class.java)

            runOnUiThread {
                recyclerView_main.adapter = MainAdapter(homeFeed)
            }


        }

        override fun onFailure(call: Call, e: IOException) {
            println("Failed to execute request")
        }
    })
 }

我尝试了 10.0.2.2 ip 仍然相同,我可以使用代码中的地址从浏览器访问文件

【问题讨论】:

    标签: json kotlin gson okhttp


    【解决方案1】:

    如果您至少发布异常消息会很有帮助。也许……

    println("Failed to execute request: ${e.message}")
    

    另外,请看Stack Overflow's question guidance

    但是,只是猜测......

    这可能与您的本地服务器以及它如何进行内容协商有关。如果 php 页面确实提供 JSON(而不是呈现 HTML),那么您可以尝试在请求中添加 accept 标头。

    val request = Request.Builder()
        .url(url)
        .header("Accept", "application/json")
        .build()
    

    【讨论】:

      猜你喜欢
      • 2012-02-12
      • 1970-01-01
      • 2019-02-02
      • 2021-08-30
      • 1970-01-01
      • 2019-05-28
      • 2016-11-05
      • 2020-03-09
      • 1970-01-01
      相关资源
      最近更新 更多