http - 发送 POST 请求时出现意外的 EOF

标签 http post go

我在使用 http 包发送简单的 POST 请求时遇到一些问题:

var http_client http.Client

req, err := http.NewRequest("POST", "http://login.blah", nil)
if err != nil {
  return errors.New("Error creating login request: " + err.Error())
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
body := fmt.Sprintf("?username=%s&password=%s&version=%d", client.Username, client.Password, launcherVersion)
fmt.Println("Body:", body)
req.Body = ioutil.NopCloser(bytes.NewBufferString(body))
req.ParseForm()
resp, err := http_client.Do(req)

if err != nil {
  return errors.New("Error sending login request: " + err.Error())
}

我从打印中看到了正确的正文:

Body: ?username=test&password=test&version=13

但是 60 秒后,我得到:

Error sending login request: unexpected EOF

我确定这与我设置请求正文的方式有关,因为用 Wireshark 观看它会显示该请求,该请求立即发出,Content-Length 为 0没有 body 。

POST / HTTP/1.1
Host: login.blah
User-Agent: Go http package
Content-Length: 0
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip

最佳答案

您的 body 字符串看起来像 URL 的末尾,就像您在 GET 请求中发送参数一样。

服务器可能期望您的 POST 请求正文采用 multipart/form-data 格式,如 http://www.w3.org/TR/html401/interact/forms.html#form-data-set 中定义。

我认为你应该这样做

  • 使用multipart.Writer塑造你的 body 。

  • 使用PostForm如包示例所示:

    resp, err := http.PostForm("http://example.com/form",
        url.Values{"key": {"Value"}, "id": {"123"}})
    

关于http - 发送 POST 请求时出现意外的 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10953933/

相关文章:

go - 从 Go 代码构建 Docker 镜像

http - 关于 Wireshark 和 http/tcp 流

java httpserver处理POST请求并读取html表单信息

c# - 验证在单元测试中失败

走吧,路很崎岖。感谢帮助

go - 静态文件 url 意外行为

html - RESTful URL 中的输出格式是如何编码的?

http - 如何防止 http.ListenAndServe 改变静态输出中的样式属性?

c# - 点对点去中心化网络——向所有点发送消息

iphone - 使用 NSURLConnection 的 iPhone 的 HTTPS POST 在某些文件大小范围内挂起