Home >Backend Development >Golang >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?

Linda Hamilton
Linda HamiltonOriginal
2024-12-21 22:19:19887browse

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.

The above is the detailed content of Why am I getting a 400 BAD REQUEST when sending URL-encoded POST requests?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn