You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Volley发起POST请求遇unsupported_grant_type错误求解决

解决Volley POST请求返回"unsupported_grant_type"的问题

这个问题我之前也踩过坑!大概率是请求参数的格式不符合服务端要求导致的,下面给你拆解原因和解决思路:

核心原因

大多数OAuth2的/token接口期望请求参数以application/x-www-form-urlencoded(表单编码)的格式传递,而你用的JsonObjectRequest默认会把参数序列化成JSON格式,同时设置请求头的Content-Type为application/json。服务端接收到JSON格式的参数后,无法识别grant_type字段,就会返回unsupported_grant_type错误。

解决步骤

把请求改成表单编码格式即可,推荐使用StringRequest来实现:

修改后的Kotlin代码示例

val url: String = "http://192.168.254.80/MpDS/api/token"
// 构建请求参数
val params = HashMap<String, String>().apply {
    put("username", "你的用户名")
    put("password", "你的密码")
    put("grant_type", "password") // 注意:这个值要和服务端要求一致,比如可能是client_credentials等
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main) // 补充你的布局设置

    val requestQueue = Volley.newRequestQueue(this)

    val stringRequest = object : StringRequest(
        Method.POST, url,
        // 请求成功回调
        Response.Listener<String> { response ->
            try {
                // 把响应字符串解析成JSON对象处理
                val jsonResponse = JSONObject(response)
                // 这里可以获取token等数据,比如 jsonResponse.getString("access_token")
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        },
        // 请求失败回调
        Response.ErrorListener { error ->
            error.printStackTrace()
        }
    ) {
        // 重写getParams返回表单参数
        override fun getParams(): MutableMap<String, String> {
            return params
        }

        // 重写getHeaders设置正确的Content-Type
        override fun getHeaders(): MutableMap<String, String> {
            return hashMapOf("Content-Type" to "application/x-www-form-urlencoded")
        }
    }

    requestQueue.add(stringRequest)
}

额外排查点

如果修改后还是报错,可以检查这几点:

  • grant_type取值是否正确:服务端可能只接受特定值(比如password、client_credentials、refresh_token),一定要和服务端文档匹配,不能拼写错误。
  • 参数拼写是否正确:比如把grant_type写成granttype,服务端会识别不到这个参数,同样会返回该错误。
  • 是否需要额外身份验证:部分服务端要求传递client_id和client_secret,可能需要把这两个参数加入表单,或者通过Authorization请求头做Basic认证(把client_id:client_secret用Base64编码后放在头里)。

内容的提问来源于stack exchange,提问作者RAL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:42:59