2017-02-19 5 views
0

Redditには、Oauth2用のAPIエンドポイントがあり、アクセストークンを取得するために適切なヘッダーとデータでPOSTを実行する必要があります。ここに私のコードは次のとおりです。gorequestで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のルールを次のようしています。だから、いただきました!間違っ

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()) 

を私の囲碁のコードで:

ここで働く私の同等のpythonコードはありますか?私がやっている間違いはありますか?

私はテストすることができます/デバッグ私の要求と私が行っていたら、私はそうするため curlまたは goコードを取得することができます主な理由は、他のオプション以外にも、例えば、これはやって出力され、 pawクライアントを使用している
+0

「github.com/parnurzeal/gorequest」を使用する必要がありますか? "net/http"のリクエストはいいですか? – Tanaike

答えて

0

一般的な投稿リクエスト:

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)) 
} 
関連する問題