使用FormData和身份验证在Go中发出POST请求

时间:2018-10-28 18:45:25

标签: go

我目前正在尝试使用示例curl命令curl -u {client_id}:{client_secret} -d grant_type=client_credentials https://us.battle.net/oauth/token与OAuth api进行接口。我当前的go文件是:

package main

import (
    "bytes"
    "fmt"
    "mime/multipart"
    "net/http"
)

func checkErr(err error) bool {
    if err != nil {
        panic(err)
    }
    return true
}

func authcode(id string, secret string, cli http.Client) string {
    //un(trace("authcode"))
    var form bytes.Buffer
    w := multipart.NewWriter(&form)
    _, err := w.CreateFormField("grant_type=client_credentials")
    checkErr(err)
    req, err := http.NewRequest("POST", "https://us.battle.net/oauth/token", &form)
    checkErr(err)
    req.SetBasicAuth(id, secret)
    resp, err := cli.Do(req)
    checkErr(err)
    defer resp.Body.Close()
    json := make([]byte, 1024)
    _, err = resp.Body.Read(json)
    checkErr(err)
    return string(json)
}

func main() {
    //un(trace("main"))
    const apiID string = "user"
    const apiSecret string = "password"
    apiClient := &http.Client{}
    auth := authcode(apiID, apiSecret, *apiClient)
    fmt.Printf("%s", auth)
}

运行此命令时,我得到{"error":"invalid_request","error_description":"Missing grant type"}

的响应

供参考,api流状态:
“要请求访问令牌,应用程序必须向令牌URI发出包含以下多部分形式数据的POST请求:grant_type = client_credentials

应用程序必须使用client_id作为用户并使用client_secret作为密码来传递基本的HTTP身份验证凭据。“
预期的响应是一个json字符串,其中包含访问令牌,令牌类型,以秒为单位的到期时间以及该令牌可用的功能范围

1 个答案:

答案 0 :(得分:0)

在curl手册中,我们有:

       -d, --data <data>
          (HTTP)  Sends  the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and
          presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded.   Compare  to
          -F, --form.

请注意content-type application/x-www-form-urlencoded部分。

相对于:

       -F, --form <name=content>
          (HTTP SMTP IMAP) For HTTP protocol family, this lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl  to
          POST data using the Content-Type multipart/form-data according to RFC 2388.

因此,根据您的curlmime/multipart可能不是您要查找的,您应该使用Client.PostForm,该手册来自于我们的手册:

The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use NewRequest and Client.Do.