如何通过http客户端发送投递表单数据



我的post请求有问题,需要通过http客户端发送简单的表单数据。http:。PostForm((不好,因为我需要设置自己的用户代理和其他头。

这是的样本

func main() {
formData := url.Values{
"form1": {"value1"},
"form2": {"value2"},
}
client := &http.Client{}

//Not working, the post data is not a form
req, err := http.NewRequest("POST", "http://test.local/api.php", strings.NewReader(formData.Encode()))
if err != nil {
log.Fatalln(err)
}

req.Header.Set("User-Agent", "Golang_Super_Bot/0.1")

resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}

log.Println(string(body))
}

您还需要将内容类型设置为application/x-www-form-urlencoded,这与Value.Encode()使用的编码相对应。

req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

这是Client.PostForm.所做的事情之一

最新更新