"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why am I getting a 400 BAD REQUEST when sending URL-encoded POST requests?

Why am I getting a 400 BAD REQUEST when sending URL-encoded POST requests?

Published on 2024-12-22
Browse:331

Why am I getting a 400 BAD REQUEST when sending URL-encoded POST requests?

POST Request with URL-Encoded Payload

When constructing a POST request with URL-encoded data, it is common to encounter a 400 BAD REQUEST response, indicating that the server cannot understand the payload. This issue typically arises when the payload is provided incorrectly.

The standard library's http.NewRequest(...) method expects the payload to be provided as the third argument, which should implement the io.Reader interface. In the case of URL-encoded payload, this means it should be a string of encoded key-value pairs.

Example Code:

To correctly send URL-encoded data as a POST request using http.NewRequest(...), consider the following example:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Add("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl   resource)
 
    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(data.Encode()))
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
    bodyBytes, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(bodyBytes))
}

In this example, the URL-encoded payload is provided to the strings.NewReader function, which implements io.Reader. The request is then properly constructed and sent.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3