http - 发出自定义发布请求时出现 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)
解决方案
您没有发送内容协商标头。
内容类型
Content-Type 标头字段通过提供媒体类型和子类型标识符以及通过提供某些媒体类型可能需要的辅助信息来指定实体主体中数据的性质。在媒体类型和子类型名称之后,标头字段的其余部分只是一组参数,以属性=值表示法指定。参数的顺序并不重要。
在这种情况下,内容被编码,application/x-www-form-urlencoded
因此必须使用Content-Type
标头将其传达给服务器
请在发送请求前添加以下内容
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
推荐阅读
- java - 依赖于 JavaFX 由 Maven 构建可执行的 .jar
- flutter - 如何在 Flutter/Android Studio 中编辑运行配置?
- date - 使用 Google 脚本在 Google 表格上搜索/匹配日期,并将源范围复制到目标范围 OFFSET 从该日期开始
- python - 更新散点标记类型的方法
- sas - SAS 输入:用逗号分隔的整数
- java - 创建几乎相同的子类的两种方法?
- angular - Angular 在构建时找不到模块(仅限产品)
- solidworks - 我怎样才能平滑这个角落?
- javascript - 为什么“if”有效但“switch”无效?
- python-3.x - 十进制到二进制和连续 1 的计数