首页 > 解决方案 > 发出自定义发布请求时出现 400 错误请求

问题描述

我相信问题在于 url 值。当我将此发布到服务器时,我会收到一个 400 Bad Request: 告诉我我需要一个电子邮件值。这使我相信 editForm 中的电子邮件值被错误地解析,或者 first_value 是,然后“污染”其余部分。我已经看到了:Make a URL-encoded POST request using `http.NewRequest(...)`并相信我做的一切都是正确的,但这让我失望。

editForm := url.Values{}
editForm.Add("first_name", "supercool")
editForm.Add("email", "wow@example.com")
editForm.Add("username", "foo")

req, err := http.NewRequest(http.MethodPost, urlEndpoint, strings.NewReader(editForm.Encode()))
if err != nil {
    log.Fatalln(err)
}
client := http.Client{}
resp, err := client.Do(req)

我已经仔细检查了应该调用什么表单数据,但我看不到错误。作为参考,这个 python 代码可以工作。

cn = {
    "first_name": "supercool",
    "email": "wow@example.com",
    "username": "foo"
}
r = requests.post(urlEndpoint, data = cn)

标签: httpgo

解决方案


您没有发送内容协商标头。

内容类型

Content-Type 标头字段通过提供媒体类型和子类型标识符以及通过提供某些媒体类型可能需要的辅助信息来指定实体主体中数据的性质。在媒体类型和子类型名称之后,标头字段的其余部分只是一组参数,以属性=值表示法指定。参数的顺序并不重要。

在这种情况下,内容被编码,application/x-www-form-urlencoded因此必须使用Content-Type标头将其传达给服务器

请在发送请求前添加以下内容

 r.Header.Add("Content-Type", "application/x-www-form-urlencoded")

推荐阅读