我尝试在POST请求的正文中发送一些JSON,但始终收到错误400。 从邮递员发送时,相同的请求也可以正常工作。两者之间有什么区别? 为什么没有调用getBody()?
注意:给出的URL不是真实的。
queue = Volley.newRequestQueue(context)
val URL: String = "https://robotnik.pythonanywhere.com/user/"
val userModel: UserModel = UserModel(
name = "name",
lastName = "lastname",
username = "username",
email = "email",
isStudent = true,
isTeacher = false
)
val gson: Gson = Gson()
val jsonElement: JsonElement = gson.toJsonTree(userModel)
val stringRequest = object : StringRequest(
Method.POST,
URL,
Response.Listener<String> {
Toast.makeText(context, "GOT RESPONSE FROM SERVER", Toast.LENGTH_SHORT ).show()
},
Response.ErrorListener {error ->
Toast.makeText(context, "Something went wrong with request. ERROR: $error", Toast.LENGTH_LONG ).show()
})
{
override fun getBodyContentType(): String {
return "application/json; charset=utf-8"
}
@Throws(AuthFailureError::class)
override fun getBody(): ByteArray {
return jsonElement.asJsonObject.toString().toByteArray(StandardCharsets.UTF_8)
}
}
queue.add(stringRequest)