如何结合使用 localhost 和 retrofit 来测试 android 应用程序 kotlin

how to use localhost in conjunction with retrofit for testing of android apps kotlin

我正在使用 xammp 测试我的后端脚本,我只需要 get 一些 JSON 改造。我试过在线学习教程,但无济于事。我收到错误代码

    java.net.ConnectException: Failed to connect to /127.0.0.1:80

无论我是使用 localhost 作为 localhost/xammp 服务器的 baseURL 还是 IP 地址,还是我是否明确使用该端口,我都会收到此错误消息或类似上述内容。 edit:仔细检查错误日志后,它还说:

     Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)

     Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 80) from /127.0.0.1 (port 58156) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)

这跟这有什么关系吗?

我满jsontest.php

{
    "resoponse": {
        "check": "ahhhhhhhh"
    },
    "Mlist": [{
            "text1": "text1a",
            "text2": "text2a",
            "text3": "text3a"
        },
        {
            "text1": "text1b",
            "text2": "text2b",
            "text3": "text3b"
        },
        {
            "text1": "text1c",
            "text2": "text2c",
            "text3": "text3c"
        }
    ]
}

简单api.kt

interface SimpleApi {
    @GET("jsontest.php")
    suspend fun phonehome(): Phone
}

主要fragment.kt

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_main, container, false)
        mUserViewModel = ViewModelProvider(this).get(ViewModel::class.java)

            //other code

            TestGet()

        return view
    }
val BASE_URL = "http://127.0.0.1/"
    private fun TestGet() {

        val api = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(SimpleApi::class.java)

        GlobalScope.launch(Dispatchers.IO) {
          // doing stuff with response
        }
}

如果您能指出正确的方向,我将不胜感激

谢谢。

你的服务器是80端口吗?默认情况下,它在 8000 或 8080 上,如果是这种情况,您的 URL (BASE_URL) 将如下所示: http://127.0.0.1:xxxx/,xxxx 是您的端口号,还要检查您的 IP 地址并使确保您可以从计算机外部访问 URL。

您的服务器 运行 与您的 Android 应用在同一设备上吗?只有这样你才能使用 localhost/127.0.0.1.