如何通过http客户端发送post表单数据?

How to send post form data through a http client?

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

这是示例

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 所做的事情之一。