How to Send POST Data Using wget?
The wget command-line utility is widely known for
downloading files, but it also serves as a powerful tool for sending
HTTP POST requests. By utilizing specific flags like
--post-data and --post-file, users can
transmit data payloads directly to a server from the terminal. This
article provides a straightforward guide on how to construct these
requests, handle different data formats, and include necessary HTTP
headers for API testing and web automation.
Sending Data Directly from the Terminal
The most common way to send a POST request with wget is
by using the --post-data flag. This method requires you to
pass the data payload as a string directly within your command line.
- Syntax:
wget --post-data="string_data" URL - Standard URL-encoded Example:
wget --post-data="username=john_doe&status=active" http://example.com/api/userWhen you use --post-data, wget
automatically sets the Content-Type header to
application/x-www-form-urlencoded. The server processes
this exactly like a standard HTML form submission.
Sending Data from a File
If your payload is too large, complex, or contains characters that
are difficult to escape in the terminal, you can store the data in a
file and transmit it using the --post-file flag.
- Syntax:
wget --post-file="path/to/file" URL - Example:
wget --post-file="payload.txt" http://example.com/api/submitThis approach is highly efficient for automation scripts and cron jobs, as it keeps the command line clean and allows you to reuse structured data payloads.
Sending JSON Data with wget
While wget defaults to form-encoded data, modern APIs
frequently require JSON payloads. To successfully send JSON, you must
manually override the default Content-Type header using the
--header flag.
Here is how to structure a JSON POST request:
wget --header="Content-Type: application/json" --post-data='{"name": "Alice", "role": "admin"}' http://example.com/api/v1/usersNote: Pay close attention to quotes when writing JSON in the terminal. Use single quotes (
') around the entire--post-datavalue so that the double quotes (") inside the JSON string do not conflict with your shell environment.
Advanced Configurations
When interacting with APIs, you often need to provide authentication
tokens or custom metadata alongside your data payload. You can stack
multiple --header flags to achieve this.
wget --header="Content-Type: application/json" \
--header="Authorization: Bearer YOUR_API_TOKEN" \
--post-file="data.json" \
http://example.com/api/secure-endpointBy mastering these flags, you can transform wget from a
simple file downloader into an efficient tool for interacting with web
services and testing REST APIs.