英文:
How to send a POST request in 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)
英文:
I am trying to make a POST request but I can't get it done. Nothing is received on the other side.
Is this how it is supposed to work? I'm aware of the PostForm
function but I think I can't use it because it can't be tested with httputil
, right?
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)
答案1
得分: 171
你的想法基本正确,只是发送表单的部分有误。表单应该放在请求的正文中。
req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))
英文:
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()))
答案2
得分: 68
我知道这是旧的,但这个答案在搜索结果中出现了。对于下一个人来说,提出的和接受的答案是有效的,但是问题中最初提交的代码比所需的低级别。没人有时间搞这个。
//一行的POST请求/响应...
response, err := http.PostForm(APIURL, url.Values{
"ln": {c.ln},
"ip": {c.ip},
"ua": {c.ua}})
//好的,继续...
if err != nil {
//处理postform错误
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
//处理读取响应错误
}
fmt.Printf("%s\n", string(body))
https://golang.org/pkg/net/http/#pkg-overview
英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论