Android Kotlin-从URL获取简单字符串

时间:2018-08-19 06:29:09

标签: android kotlin android-volley

我简直不敢回答!

我怎么能像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"

2 个答案:

答案 0 :(得分:1)

这有效

    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)

答案 1 :(得分:0)

在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")
        }

    })

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