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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?