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

使用GoLang调用Reddit API获取Bearer Token时遇unsupported_grant_type错误

解决GoLang调用Reddit API获取Token时的"unsupported_grant_type"错误

你遇到的问题核心是请求体格式不匹配:Reddit的/api/v1/access_token接口要求请求体使用application/x-www-form-urlencoded(表单编码)格式,但你的代码里用了JSON编码发送数据——哪怕设置了Content-Type头,实际数据格式还是错的,所以API无法识别grant_type参数,返回错误。

Postman和Python能成功,是因为它们默认或者你正确配置了用表单格式传递参数,而非JSON。

修正代码的关键步骤:

  • 去掉JSON相关的结构体和编码逻辑,改用url.Values构建表单参数
  • 将表单参数编码为符合application/x-www-form-urlencoded格式的字节流作为请求体

修正后的完整代码:

import (
    "bytes"
    "io"
    "log"
    "net/http"
    "net/url"
)

func GetUserToken(username string, password string) string {
    // 构建表单参数
    formData := url.Values{}
    formData.Set("username", username)
    formData.Set("password", password)
    formData.Set("grant_type", "password")

    // 将表单编码为字节流
    reqBody := bytes.NewBufferString(formData.Encode())

    r, err := http.NewRequest("POST", "https://www.reddit.com/api/v1/access_token", reqBody)
    if err != nil {
        panic(err)
    }

    r.Header.Add("User-Agent", "my_unique_user_agent/0.0.1")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")

    app_id := "app.id"
    secret := "secret_string"
    r.SetBasicAuth(app_id, secret)

    client := &http.Client{}
    res, err := client.Do(r)
    if err != nil {
        panic(err)
    }

    defer res.Body.Close()
    responseData, err := io.ReadAll(res.Body)
    if err != nil {
        panic(err)
    }
    log.Println("Response Status:", res.Status)
    log.Println(string(responseData))

    return string(responseData)
}

关键修改说明:

  1. 用url.Values构建所有需要的表单参数,包括username、password、grant_type
  2. 通过formData.Encode()将参数转为key1=value1&key2=value2格式的字符串,再包装成bytes.Buffer作为请求体
  3. 移除了原来的JSON结构体和json.NewEncoder相关代码,确保请求体格式符合API要求

这样修改后,请求格式就和Postman、Python里的正确请求一致了,应该能正常获取到Bearer Token。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:55:00