Android Kotlin-从URL获取简单字符串 [英] Android kotlin - get simple string from url

查看:849
本文介绍了Android Kotlin-从URL获取简单字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我简直不敢回答!

我怎样才能像https://ipinfo.io/ip中的IP一样,只是一个简单的字符串?

How can I get like the IP from https://ipinfo.io/ip which would be nothing but a simple string?

这是我尝试过的:

    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"

推荐答案

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

In android all network calls are async and doesn't execute on main thread, Volley follows the same methodology and makes it's network call async, So in your code "Log.d("letsSee", soo)" statement won't wait for Volley to execute network call instead it will get executed

所以您必须创建这样的回调接口

So you have to create callback interface like this

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

}

然后执行一个这样的功能

and then make one function like this

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()函数

and call this getMyIp() function like this

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

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

    })

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

ou can also implement ApiResponse interface at class level

这篇关于Android Kotlin-从URL获取简单字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆