Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send post form data through a http client?

Tags:

http

http-post

go

I have a problem with post request, needed to send simple form data through http client. http.PostForm() is not ok because I need to set my own user agent and other headers.

Here is the sample

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))
}
like image 569
Stairdeck Avatar asked Mar 13 '26 11:03

Stairdeck


1 Answers

You also need to set the content type to application/x-www-form-urlencoded which corresponds to the encoding used by Value.Encode().

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

This is mentioned as one of the things done by Client.PostForm.

like image 148
Marc Avatar answered Mar 16 '26 06:03

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!