2012-06-08 73 views
0

我有一些麻煩,發送與HTTP包一個簡單的POST請求:意外結束時發送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 

我敢肯定它是與我如何設置請求主體,因爲看着它的機智h Wireshark向我顯示請求,該請求立即結束,Content-Length爲0,沒有任何內容。

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 

回答

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"}}) 
    
+1

不知道我做錯了前當我試圖http.PostForm,但我只是試圖再次,它似乎已經奏效!謝謝! – Seventoes