如何在Android中使用Volley进行身份验证

时间:2018-07-24 08:58:46

标签: android android-volley

我在此URL中有一个Web服务:https://server_IP:9443/api/v1/ssids.json/ 但需要登录此页面:https://server_IP:9443/login

当我使用标头中的凭据发出请求时,我收到“意外响应代码401”

所以我如何进行身份验证并获取json。

这是我的代码:

  val request = object : StringRequest(Request.Method.GET, url, Response.Listener { response ->
        if (response != null) {
            Log.e("Your Array Response", response)
        } else {
            Log.e("Your Array Response", "Data Null")
        }
    }, Response.ErrorListener { error -> Log.e("error is ", "" + error) }) {


    override fun getHeaders() : Map<String, String> {
        val username ="admin"
        val password = "admin"
        val auth = "$username:$password"
        var data = auth.toByteArray()
        var base64 = Base64.encodeToString(data, Base64.NO_WRAP)
        var headers = HashMap<String, String>()
        headers.put("Authorization",base64)
        headers.put("accept-language","EN")
        headers.put("Content-type","application/json")
        headers.put("Accept","application/json")
        return headers
        }
    }
    val queue = Volley.newRequestQueue(this)
    queue.add(request)

0 个答案:

没有答案