Reddit有一个Oauth2的API端点,我需要使用正确的标头和数据进行POST以获取访问令牌。这是我的代码:
package main
import (
"github.com/parnurzeal/gorequest"
"fmt"
)
func main() {
app_key := "K...A"
app_secret := "3...M"
ua_string := "script:bast:0.1 (by /u/a...h)"
username := "a...h"
password := "..."
r := gorequest.New().SetBasicAuth(app_key, app_secret).Set("User-Agent", ua_string)
resp, body, errs := r.Post("https://www.reddit.com/api/v1/access_token").Send(
map[string]string{
"grant_type": "password",
"username": username,
"password": password,
},
).End()
if errs != nil {
fmt.Println(errs)
}
fmt.Println(resp)
fmt.Println(resp.StatusCode)
fmt.Println(body)
}
但是它没有用,我得到了:{"message": "Too Many Requests", "error": 429}
我根本没有提出太多请求,我也遵循API规则。
这是我的等效python代码:
import requests
import requests.auth
app_key = "K...A"
app_secret = "3...M"
ua_string = "script:bast:0.1 (by /u/a...h)"
username = "a...h"
password = "..."
client_auth = requests.auth.HTTPBasicAuth(app_key, app_secret)
post_data = {"grant_type": "password", "username": username,
"password": password}
headers = {"User-Agent": ua_string}
response = requests.post("https://www.reddit.com/api/v1/access_token",
auth=client_auth, data=post_data, headers=headers)
print(response.json())
我的Go代码有什么问题?我有什么错误吗?
答案 0 :(得分:-1)
我一直在使用paw客户端,主要是因为我可以测试/调试我的请求,一旦完成,我可以获得curl
或go
代码,除此之外选项,例如,这是执行通用发布请求的输出:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func sendGetRepos() {
// Create client
client := &http.Client{}
// Create request
req, err := http.NewRequest("POST", "https://api.endpoint.tld", nil)
// Headers
req.Header.Add("Authorization", "Bearer ***** Hidden credentials *****")
// Fetch Request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Failure : ", err)
}
// Read Response Body
respBody, _ := ioutil.ReadAll(resp.Body)
// Display Results
fmt.Println("response Status : ", resp.Status)
fmt.Println("response Headers : ", resp.Header)
fmt.Println("response Body : ", string(respBody))
}