如何解决如何在Go中使用application / x-www-form-urlencoded内容类型执行GET请求?
基本上,我需要在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标头。
解决方法
您误解了application/x-www-form-urlencoded
标头,您应该在此处传递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())))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。