所以我对围棋有点新手,请原谅我的无知。我正在尝试使用oauth2对twitter进行简单的REST API调用,用于"仅应用程序"调用,但我一直将"无效或过期的令牌"作为错误返回。
有人有设置这样的东西的经验吗?
响应为:{"errors":〔{"code":89,"message":"无效或过期的令牌。"}〕}
package main
import "fmt"
import "encoding/base64"
import "io/ioutil"
import "time"
import "golang.org/x/oauth2"
func main() {
config := &oauth2.Config{
Endpoint: oauth2.Endpoint{
AuthURL: "https://api.twitter.com/oauth2/token",
TokenURL: "https://api.twitter.com/oauth/request_token",
},
}
accessToken := base64.StdEncoding.EncodeToString([]byte("{Consumer Key (API Key)}:{Consumer Secret (API Secret)}"));
token := &oauth2.Token{
AccessToken: accessToken,
Expiry: time.Now().Add(time.Duration(24)*time.Hour)
}
httpClient := config.Client(oauth2.NoContext, token)
resp, err := httpClient.Get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=google")
if (err != nil) {
fmt.Printf("Error: %s", err)
}
defer resp.Body.Close();
body, err := ioutil.ReadAll(resp.Body);
if (err != nil) {
fmt.Printf("Error: %s", err)
}
fmt.Printf("Access Token: %snToken: %snResponse: %sn", accessToken, token, body)
}
所以我没有利用客户端凭据oauth2包。我能够让它发挥作用。
希望这能帮助未来的某个人:
package main
import "fmt"
import "io/ioutil"
import "golang.org/x/oauth2"
import "golang.org/x/oauth2/clientcredentials"
func main() {
config := &clientcredentials.Config{
ClientID: "{App Key}",
ClientSecret: "{App Secret}",
TokenURL: "https://api.twitter.com/oauth2/token",
}
tok, err := config.Token(oauth2.NoContext)
httpClient := config.Client(oauth2.NoContext)
resp, err := httpClient.Get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=google")
if (err != nil) {
fmt.Printf("Error: %s", err)
}
defer resp.Body.Close();
body, err := ioutil.ReadAll(resp.Body);
if (err != nil) {
fmt.Printf("Error: %s", err)
}
fmt.Printf("Access Token: %snToken: %snResponse: %sn", tok, body)
}