kotlin - Kotlin:使用基本身份验证和参数发布请求导致服务器错误
问题描述
我正在使用 kotlin android 应用程序连接到具有基本授权的宁静服务。标题Authorization
已检查。被params
检查。url
被检查。还检查了防火墙。但我遇到了com.android.volley.ServerError
错误。这个值在Postman
. 这是我的代码的一部分:
val textView = findViewById<TextView>(R.id.editTextResponse)
val queue = Volley.newRequestQueue(applicationContext)
val url = ApiUrls.CustomerAuthenticate;
// Request a string response from the provided URL.
val stringRequest = object : StringRequest(
Request.Method.POST, url,
Response.Listener<String> { response ->
// Display the first 500 characters of the response string.
textView.text = "Response is: ${response.substring(0, 500)}"
},
Response.ErrorListener { error ->
Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show()
textView.text = "That didn't work!"
}) {
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
val authorizationString = String.format(
"%s:%s",
"username",
"password"
)
val authorizationByte = authorizationString.toByteArray()
val base64Encoded = Base64.encodeToString(authorizationByte, Base64.NO_WRAP)
headers["Authorization"] = String.format("Basic %s", base64Encoded)
return headers
}
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params["username"] = "username"
params["password"] = "password"
return params
}
}
stringRequest.setRetryPolicy(
DefaultRetryPolicy(
45000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
)
// Add the request to the RequestQueue.
queue.add(stringRequest)
解决方案
经过一番挣扎找到了答案。只需更换
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params["username"] = "username"
params["password"] = "password"
return params
}
和
override fun getBodyContentType(): String {
return "application/json"
}
override fun getBody(): ByteArray {
val params2 = HashMap<String, String>()
params2.put("username", "username")
params2.put("password", "password")
return JSONObject(params2 as Map<*, *>).toString().toByteArray()
}
推荐阅读
- excel - 将工作表名称添加到 VBA 中的所有公式引用
- mysql - MySQL 查询性能非常依赖于 Where 子句
- c# - 在数据类型不固定的情况下读取 SQL 查询的结果
- python - 熊猫数据框中每个时期的一个图
- tableau-api - 如何使用 Tableau 修复字段或列值中的拼写错误
- css - 滑动手势菜单
- regex - 需要从 cmd 输出中截断无用的文本
- sql - oracle如何从case语句中获取函数返回结果
- sql-server - SQL Server Management Studio 拒绝查看对所有数据库的访问权限,但用户有权访问但没有使用户成为所有者的数据库
- ios - Nativescript-Vue IOS安全区布局问题