如何通过http客户端发送邮寄表格数据?

问题描述

我对发布请求有疑问,需要通过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完成的事情之一。