如何在Go中发送POST请求?


83

我正在尝试发出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)


您要测试httputil什么?
JimB 2014年

http处理程序。我认为这是一种e2e测试

Answers:


132

您基本上有正确的想法,只是发送错误的表格。该表格属于请求的正文。

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

15
没错...刚才我正在看...看来您不仅需要阅读godoc的源代码来了解其应如何工作。

41

我知道这很老,但是这个答案出现在搜索结果中。对于下一个人-提出并接受的答案有效,但是最初在问题中提交的代码比所需的级别低。没有人有时间这样做。

//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")
jsnfwlr

11
Content-Type报头被自动设置为application/x-www-form-urlencoded通过PostForm:根据golang.org/pkg/net/http/#PostForm
查Wooters

如果要向其添加任何其他标头(例如基本授权),是否有办法?
huggie

@huggie不,源文档golang.org/src/net/http/client.go?s=28199:28281#L848指出:“要设置其他标头,请使用NewRequest和Client.Do。”
CenterOrbit
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.