亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Go 中使用 application/x-www-form 執行 GET 請求?

如何在 Go 中使用 application/x-www-form 執行 GET 請求?

Go
鳳凰求蠱 2022-06-27 15:48:34
基本上,我需要在 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 functionclient := &http.Client{}payload := Payload{    Email: "[email protected]",}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 標頭。
查看完整描述

1 回答

?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

你誤解了application/x-www-form-urlencoded標題,你應該在這里傳遞一個 URL 參數。看一個例子:


import (

  ...

  "net/url"

  ...

)


data := url.Values{}

data.Set("email", "[email protected]")

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


查看完整回答
反對 回復 2022-06-27
  • 1 回答
  • 0 關注
  • 190 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號