如何在 Go 中发送 POST 请求? [英] How to send a POST request in Go?

查看:150
本文介绍了如何在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆