dsj60862 2016-10-12 19: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 19: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")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)