登录
首页 >  Golang >  Go问答

使用表单数据和身份验证在 Go 中发出 POST 请求

来源:stackoverflow

时间:2024-03-10 10:15:26 150浏览 收藏

本篇文章给大家分享《使用表单数据和身份验证在 Go 中发出 POST 请求》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我目前正在尝试使用示例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 字符串,其中包含访问令牌、令牌类型、过期时间(以秒为单位)以及该令牌可用的函数范围


解决方案


从curl手册中我们可以得到:

-d, --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 
          (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.

今天关于《使用表单数据和身份验证在 Go 中发出 POST 请求》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>