dsj60862 2016-10-12 11:15
浏览 262
已采纳

使用标头在Golang中发送POST请求

I create my form like this:

form := url.Values{}
form.Add("region", "San Francisco")
if len(params) > 0 { 
    for i := 0; i < len(params); i += 2 { 
        form.Add(params[i], params[i+1])
    }
    testLog.Infof("form %v", form)

Now if I use

resp, err = http.PostForm(address+r.Path, form)

then everything works fine, I get back a response with an expected cookie.

However, I would like to to add a header in which case I can't use PostForm hence I created my POST request manually like:

req, err := http.NewRequest("POST", address+r.Path, strings.NewReader(form.Encode()))

Then I add stuff to the header and send the request

req.Header.Add("region", "San Francisco") 
resp, err = http.DefaultClient.Do(req)

But the form is not received and my response does not contain any cookie.

When I print the req, it looks like the form is nil:

&{POST http://localhost:8081/login HTTP/1.1 1 1 map[Region:[San Francisco]] {0xc420553600} 78 [] false localhost:8081 map[] map[] <nil> map[]   <nil> <nil> <nil> <nil>}
  • 写回答

1条回答 默认 最新

  • doujing5150 2016-10-12 11:28
    关注

    You need to add a content type to your request.

    You said http.PostForm worked so let's look at the source of that:

    func PostForm(url string, data url.Values) (resp *Response, err error) {
        return DefaultClient.PostForm(url, data)
    }
    

    OK so it's just a wrapper around the PostForm method on the default client. Let's look at that:

    func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) {
        return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
    }
    

    OK it's calling the Post method and passing in "application/x-www-form-urlencoded" for bodyType and doing the same thing for the body that you're doing. Let's look at the Post method

    func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error) {
        req, err := NewRequest("POST", url, body)
        if err != nil {
            return nil, err
        }
        req.Header.Set("Content-Type", bodyType)
        return c.doFollowingRedirects(req, shouldRedirectPost)
    }
    

    So the solution to your problem is to add

    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 我在使用VS编译并执行之后,但是exe程序会报“无法定位程序输入点_kmpc_end_masked于动态链接库exe上“,请问这个问题有什么解决办法吗
  • ¥15 el-select光标位置问题
  • ¥15 单片机 TC277 PWM
  • ¥15 在更新角色衣服索引后,Sprite 并未正确显示更新的效果该如何去解决orz(标签-c#)
  • ¥15 VAE代码如何画混淆矩阵
  • ¥15 求遗传算法GAMS代码
  • ¥15 雄安新区高光谱数据集的下载网址打不开
  • ¥66 android运行时native和graphics内存详细信息获取
  • ¥15 rk3566 Android11 USB摄像头 微信
  • ¥15 torch框架下的强化学习DQN训练奖励值浮动过低,希望指导如何调整
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部