http - 如何在 Go 中使用 application/x-www-form-urlencoded content-type 执行 GET 请求?

标签 http go get content-type

基本上,我需要在 Go 中实现以下方法 - https://api.slack.com/methods/users.lookupByEmail .
我试着这样做:

import (
    "bytes"
    "encoding/json"
    "errors"
    "io/ioutil"
    "net/http"
)

type Payload struct {
    Email string `json:"email,omitempty"` 
}

// assume the following code is inside some function

client := &http.Client{}
payload := Payload{
    Email: "octocat@github.com",
}

body, err := json.Marshal(payload)
if err != nil {
    return "", err
}

req, err := http.NewRequest("GET", "https://slack.com/api/users.lookupByEmail", bytes.NewReader(body))
if err != nil {
    return "", err
}

req.Header.Add("Authorization", "Bearer "+token)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

resp, err := client.Do(req)
if err != nil {
    return "", err
}

defer resp.Body.Close()
if resp.StatusCode != 200 {
    t, _ := ioutil.ReadAll(resp.Body)
    return "", errors.New(string(t))
}

responseData, err := ioutil.ReadAll(resp.Body)
if err != nil {
    return "", err
}

return string(responseData), nil
但是我收到一个错误,即“电子邮件”字段丢失,这很明显,因为此内容类型不支持 JSON 有效负载:{"ok":false,"error":"invalid_arguments","response_metadata":{"messages":["[ERROR] missing required field: email"]}} (type: string)我找不到如何在 GET 请求中包含发布表单 - http.NewRequest 和 http.Client.Get 都没有可用的发布表单参数; http.Client.PostForm 发出 POST 请求,但在这种情况下需要 GET。另外,我认为我必须在这里使用 http.NewRequest (除非存在另一种方法),因为我需要设置 Authorization header 。

最佳答案

你误解了application/x-www-form-urlencoded header ,您应该在此处传递 URL 参数。看一个例子:

import (
  ...
  "net/url"
  ...
)

data := url.Values{}
data.Set("email", "foo@bar.com")
data.Set("token", "SOME_TOKEN_GOES_HERE")


r, _ := http.NewRequest("GET", "https://slack.com/api/users.lookupByEmail", strings.NewReader(data.Encode()))
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

关于http - 如何在 Go 中使用 application/x-www-form-urlencoded content-type 执行 GET 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63737105/

相关文章:

http - 如何从 vbscript 获取电报机器人 getUpdates json 并阅读它

c# - 在 HttpWebRequest 中关闭自动重定向

php - 需要在 URL 中进行身份验证的 NSURLConnection sendSynchronousRequest

php - 无法使用 Postman 将 POST 变量发送到本地主机上的 php 脚本

javascript - 从 json 文件获取更少/匹配的对象

azure - 从 Azure 迁移到 Google Cloud Service 时出现的问题

postgresql - 如何使用 Go 提取 postgres 时间戳范围?

gorename 在 VS Code 中失败,没有明确的错误

php - 没有问号的 GET 请求

c# - C# 中的 getter 和 setter 有什么用?我如何将它们与数组一起使用?