【问题标题】:android studio volley web requestandroid studio volley 网络请求
【发布时间】:2022-01-20 08:40:24
【问题描述】:

我正在尝试向在 android studio 上返回 JSON 数组的 API 发出 get 请求,但是当我检查日志时它说有问题...(顺便说一下,我使用 kotlin)

我做错了什么?

这是我的代码:

val url = "http://example.com"
    val queue = Volley.newRequestQueue(context)

    val jsonArrayRequest = JsonArrayRequest(Request.Method.GET, url, null,
        {
            

            Log.d("notification", "successful request!")
        },
        {
            Log.d("notification", "error on request...")
        })

    queue.add(jsonArrayRequest)
}

【问题讨论】:

  • 能否附上您的响应格式示例?

标签: android android-studio android-volley


【解决方案1】:
var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
    reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8")

    val mURL = URL("<Yout API Link>?"+reqParam)

    with(mURL.openConnection() as HttpURLConnection) {
        // optional default is GET
        requestMethod = "GET"

        println("URL : $url")
        println("Response Code : $responseCode")

        BufferedReader(InputStreamReader(inputStream)).use {
            val response = StringBuffer()

            var inputLine = it.readLine()
            while (inputLine != null) {
                response.append(inputLine)
                inputLine = it.readLine()
            }
            it.close()
            println("Response : $response")
        }
    }

试试这个,它会帮助你解决问题..

【讨论】:

    【解决方案2】:

    在阅读了 Techno World 的回答后,我有了一个想法。 基本上它与 Techno World 所做的相同,但要容易得多。 我所做的是像这样打印对日志的响应:

    val url = "http://example.com"
    val queue = Volley.newRequestQueue(context)
    
    val jsonArrayRequest = JsonArrayRequest(Request.Method.GET, url, null,
        {
            Log.d("notification", "successful request!")
        },
        {response ->
            Log.d("notification", "error on request: $response")
        })
    
    queue.add(jsonArrayRequest)
    }
    

    所以当我检查日志时,我看到了这个:

    error on request: com.android.volley.noconnectionerror: java.io.ioexception: cleartext http traffic to example.com not permitted
    

    经过一番研究,我发现这是因为我使用 http 而不是 https。所以我改变了它,它工作了!

    Here 是有关该错误的堆栈溢出的原始问题,有更多方法可以解决它...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 2013-01-01
      相关资源
      最近更新 更多