Make a URL-encoded POST Request with http.NewRequest(...)
In this context, you intend to send a POST request via a predefined API with a payload formatted as application/x-www-form-urlencoded content. Instead of relying on methods like Request.ParseForm, let's delve deeper into the preferred approach using http.NewRequest(...).
To efficiently manage request headers, you opted for http.NewRequest(method, urlStr string, body io.Reader) to craft your request. While this strategy is generally sound, the key oversight lies in the handling of the payload. According to the HTTP specification, URL-encoded payloads should be provided via the body parameter, not directly appended to the URL.
Therefore, to rectify this issue, you should modify your code to include your URL-encoded payload in the body section. Here's an example:
With this modification, your code should now correctly send a URL-encoded payload in the body as required by the API. Consequently, you should expect a successful response, as indicated by a resp.Status of 200 OK.
The above is the detailed content of How to Properly Send a URL-Encoded POST Request using http.NewRequest()?. For more information, please follow other related articles on the PHP Chinese website!