dongpin2969 2018-10-27 01:44
浏览 87
已采纳

发出自定义帖子请求时出现400错误的请求

I believe the problem lies in the url values. When I post this to the server, I will a 400 Bad Request: telling me that I need to have an email value. This leads me to believe that either the email value in editForm is getting parsed incorrectly, or the the first_value is, and then "tainting" the rest. I have seen this: Make a URL-encoded POST request using `http.NewRequest(...)` and believe I am doing everything right, but this is throwing me off.

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)

I have double checked what the form data is supposed to be called, and I cannot see an error. For reference, this python code will work.

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

1条回答 默认 最新

  • drjun1994 2018-10-27 02:08
    关注

    You are not sending the content negotiation header.

    Content Type

    The Content-Type header field specifies the nature of the data in the body of an entity by giving media type and subtype identifiers, and by providing auxiliary information that may be required for certain media types. After the media type and subtype names, the remainder of the header field is simply a set of parameters, specified in an attribute=value notation. The ordering of parameters is not significant.

    Here in this case the content is encoded in application/x-www-form-urlencoded so it has to be communicated to the server using Content-Type header

    Please add the following before sending the request

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

报告相同问题?

悬赏问题

  • ¥15 怎么把512还原为520格式
  • ¥15 MATLAB的动态模态分解出现错误,以CFX非定常模拟结果为快照
  • ¥15 求高通平台Softsim调试经验
  • ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?
  • ¥15 wpf ScrollViewer实现冻结左侧宽度w范围内的视图
  • ¥15 栅极驱动低侧烧毁MOSFET
  • ¥30 写segy数据时出错3
  • ¥100 linux下qt运行QCefView demo报错
  • ¥50 F1C100S下的红外解码IR_RX驱动问题
  • ¥20 基于matlab的航迹融合 航迹关联 航迹插补