请注意,我刚从Kotlin开始
我有一个.NET API,该标准具有现成的基于.NET令牌的单用户帐户身份验证标准。
假设API已完美运行,因为已使用Postman验证了所有这些功能:
下面的代码正在工作,它是在Volley中完成的一个简单的StringRequest:
val registerRequest = object : StringRequest(Method.POST, TOKEN_URL, Response.Listener { response ->
Log.i("SmackChatAPI", response)
var tokenresponse = ""
token(tokenresponse)
}, Response.ErrorListener { response ->
Log.i("SmackChatAPI", "Something went wrong")
Log.i("SmackChatAPI", response.toString())
token("")
}){
override fun getHeaders(): MutableMap<String, String> {
var map : MutableMap<String, String> = mutableMapOf<String, String>()
//map.put("Content-Type", "application/x-www-form-urlencoded")
return map
}
override fun getBodyContentType(): String {
return "application/x-www-form-urlencoded charset=utf-8"
//return "application/json; charset=utf-8"
}
override fun getParams(): MutableMap<String, String> {
var map : MutableMap<String, String> = mutableMapOf<String, String>()
map.put("grant_type","password")
map.put("username",username)
map.put("password",password)
return map
}
}
Log.i("SmackChatAPI", "API called")
Volley.newRequestQueue(context).add(registerRequest)
验证上述代码是否有效:
但是很自然地,看到它正在接收JSON,我需要能够解析它,但是第二次我将函数调用转换为JsonObjectRequest
我得到了
com.android.volley.ClientError
以下是同一API的故障代码:
val registerRequest = object : JsonObjectRequest(Method.POST, TOKEN_URL, null, Response.Listener { response ->
var tokenresponse = response.getString("access_token")
token(tokenresponse)
}, Response.ErrorListener { response ->
Log.i("SmackChatAPI", "Something went wrong")
Log.i("SmackChatAPI", response.toString())
token("")
}){
override fun getHeaders(): MutableMap<String, String> {
var map : MutableMap<String, String> = mutableMapOf<String, String>()
//map.put("Content-Type", "application/x-www-form-urlencoded")
return map
}
override fun getBodyContentType(): String {
return "application/x-www-form-urlencoded charset=utf-8"
//return "application/json; charset=utf-8"
}
override fun getParams(): MutableMap<String, String> {
var map : MutableMap<String, String> = mutableMapOf<String, String>()
map.put("grant_type","password")
map.put("username",username)
map.put("password",password)
return map
}
}
Log.i("SmackChatAPI", "API called")
Volley.newRequestQueue(context).add(registerRequest)
正如您所看到的,所有变化都在于我现在正在使用JsonBodyRequest
有人能看到我在做什么吗?