无法从Kotlin连接到本地主机,并且可以连接到在线API

时间:2019-07-06 13:24:31

标签: json kotlin gson okhttp

遇到这个问题,我无法连接到本地主机,而无法连接到在线主机,这是我的代码,我只会在调试器中无法执行请求

 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,我可以使用代码中的地址从浏览器访问文件

1 个答案:

答案 0 :(得分:0)

如果您至少发布异常消息,这将很有帮助。也许...

public void getSerialNum(Connection connection) {
        int serialNum = 0;
        try {
            Statement stmt = connection.createStatement();

            // get the postgresql serial field value with this query
            String query = "select currval('test_id')";

            ResultSet rs;

            rs = stmt.executeQuery(query);
            if (rs.next()) {
                serialNum = rs.getInt(1);
                System.out.println("serialNum = " + serialNum);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

另外,请看看Stack Overflow's question guidance

但是,只是猜测...

这可能与您的本地服务器以及它如何进行内容协商有关。如果println("Failed to execute request: ${e.message}") 页确实提供了JSON(而不是呈现的HTML),那么您可以尝试向请求中添加php标头。

accept