使用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) }
关键修改说明:
- 用
url.Values构建所有需要的表单参数,包括username、password、grant_type - 通过
formData.Encode()将参数转为key1=value1&key2=value2格式的字符串,再包装成bytes.Buffer作为请求体 - 移除了原来的JSON结构体和
json.NewEncoder相关代码,确保请求体格式符合API要求
这样修改后,请求格式就和Postman、Python里的正确请求一致了,应该能正常获取到Bearer Token。
内容的提问来源于stack exchange,提问作者smm
相关产品推荐
相关产品推荐

