如何在Go中发送POST请求?

hey*_*hey 71 go

我正在尝试发出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)
Run Code Online (Sandbox Code Playgroud)

Inn*_*ate 119

你有大多数正确的想法,只是发送错误的表格.表单属于请求正文.

req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))
Run Code Online (Sandbox Code Playgroud)

  • 对...刚才我正在看那个......看来你需要阅读源代码,而不仅仅是godoc来了解它应该如何工作. (15认同)
  • 不要忘记在提交之前添加 Content-Type: `req.Header.Add("Content-Type", "application/x-www-form-urlencoded")` (13认同)

dlx*_*src 33

我知道这已经过时了但搜索结果却出现了这个答案.对于下一个人 - 建议和接受的答案是有效的,但最初在问题中提交的代码是低于它需要的级别.没人抽时间.

//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))
Run Code Online (Sandbox Code Playgroud)

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

  • “内容类型”标头由PostForm自动设置为“ application / x-www-form-urlencoded”,具体方法如下:https://golang.org/pkg/net/http/#PostForm (5认同)