如何在Go中发送POST请求? [英] How to send a POST request in Go?
本文介绍了如何在Go中发送POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试发出POST请求,但无法完成.另一端什么也没收到.
I am trying to make a POST request but I can't get it done. Nothing is received on the other side.
这是应该如何工作的吗?我知道 PostForm
函数,但我认为可以不要使用它,因为它无法通过 httputil
进行测试,对吧?>
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)
推荐答案
您基本上有正确的主意,只是发送错误的表格.该表单属于请求的正文.
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()))
这篇关于如何在Go中发送POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文