如何在 Go 中发送 POST 请求?

我正在尝试发送一个 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)
148198 次浏览

You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.

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

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//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