Android kotlin - 从 url 获取简单字符串

Android kotlin - get simple string from url

真不敢相信没人回答!

我怎样才能从 https://ipinfo.io/ip 获得 IP,它只不过是一个简单的字符串?

这是我试过的:

    var soo = "meh"

    val queue = Volley.newRequestQueue(this)
    val stringRequest = StringRequest(Request.Method.GET, "https://ipinfo.io/ip",
            object : Response.Listener<String> {
                override fun onResponse(response: String) {
                    // Display the first 500 characters of the response string
                    soo = response
                    Log.d("letsSee", soo) // THIS WAS CALLED SECOND: the ip
                }
            }, object : Response.ErrorListener {
        override fun onErrorResponse(error: VolleyError) {
            soo = "error occurred"
        }
    })
    queue.add(stringRequest)

    Log.d("letsSee", soo) // THIS WAS CALLED FIRST: "meh"

这是有效的

    var soo = "meh"

    val queue = Volley.newRequestQueue(this)
    val stringRequest = StringRequest(Request.Method.GET, "https://ipinfo.io/ip",
            com.android.volley.Response.Listener<String> { response ->
                soo = response
                Log.d("see again", soo)
            }, com.android.volley.Response.ErrorListener {
        // didn't work
    });
    queue.add(stringRequest)

    Log.d("letsSee", soo)

在android中,所有网络调用都是异步的,不在主线程上执行, Volley 遵循相同的方法并使其网络调用异步, 所以在你的代码中 "Log.d("letsSee", soo)" 语句不会等待 Volley 执行网络调用而是执行

所以你必须像这样创建回调接口

interface ApiResponse{
fun onSuccess(response:String)
fun onError()

}

然后像这样制作一个函数

fun getMyIp(apiResponse: ApiResponse) {
    val queue = Volley.newRequestQueue(this)
    val url = "https://ipinfo.io/ip"

    val stringRequest = StringRequest(Request.Method.GET, url,
            Response.Listener<String> { response ->
                apiResponse.onSuccess(response)
            },
            Response.ErrorListener {
                apiResponse.onError()
            }
    )

    queue.add(stringRequest)
}

并像这样调用这个 getMyIp() 函数

getMyIp(object :ApiResponse{
        override fun onSuccess(response: String) {
            Log.d("SSB Log", response)
        }

        override fun onError() {
            Log.d("SSB Log", "Error")
        }

    })

您还可以在 class 级别实现 ApiResponse 接口