用Volley的POST请求发送正文不起作用

时间:2020-05-17 11:59:34

标签: kotlin http-post postman android-volley

我尝试在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)

enter image description here

0 个答案:

没有答案