【问题标题】:How to send a POST request in Go?如何在 Go 中发送 POST 请求?
【发布时间】:2014-06-30 15:00:58
【问题描述】:

我正在尝试发出 POST 请求,但无法完成。对方什么也没有收到。

这是它应该如何工作的吗?我知道PostForm 函数,但我认为我不能使用它,因为它不能用httputil 进行测试,对吧?

hc := http.Client{}
req, err := http.NewRequest("POST", APIURL, nil)

form := url.Values{}
form.Add("ln", c.ln)
form.Add("ip", c.ip)
form.Add("ua", c.ua)
req.PostForm = form
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

glog.Info("form was %v", form)
resp, err := hc.Do(req)

【问题讨论】:

标签: go


【解决方案1】:

您的想法大多是正确的,只是表单的发送是错误的。表单属于请求正文。

req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))

【讨论】:

  • 对...刚才我在看那个...看来您需要阅读源代码而不仅仅是 godoc 才能了解它应该如何工作。
  • 提交前不要忘记添加Content-Type:req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
【解决方案2】:

我知道这是旧的,但这个答案出现在搜索结果中。对于下一个人 - 建议和接受的答案有效,但是最初在问题中提交的代码比它需要的要低。没有人有时间。

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

【讨论】:

  • 您说 OP 的代码比需要的要长,但是您的代码无法处理设置标头 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  • Content-Type 标头由PostForm 自动设置为application/x-www-form-urlencoded,根据:golang.org/pkg/net/http/#PostForm
  • 如果你想在这个上面添加任何其他的header,比如一个基本的授权,有没有办法?
  • @huggie 不,源文档golang.org/src/net/http/client.go?s=28199:28281#L848 声明:“要设置其他标头,请使用 NewRequest 和 Client.Do。”
猜你喜欢
  • 1970-01-01
  • 2012-07-04
  • 2021-01-09
  • 2017-11-17
  • 2015-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多