发送POST请求时意外的EOF

时间:2012-06-08 18:11:18

标签: 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且没有正文。< / p>

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

1 个答案:

答案 0 :(得分:3)

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

服务器可能希望POST请求的主体采用多部分/表单数据格式,如http://www.w3.org/TR/html401/interact/forms.html#form-data-set中所定义

我认为你应该

  • 使用multipart.Writer构建您的身体。

  • 在包示例中使用PostForm

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