Skip to content

Commit 11d913c

Browse files
committed
docs(client): add POST request example to client guide
Add a new section to the "Getting Started with a Client" guide that demonstrates how to make POST requests using hyper. The new section includes examples for sending plain text, binary data, and JSON in the request body, along with appropriate Content-Type headers. This addition helps users understand how to construct and send POST requests, complementing the existing GET request example.
1 parent e1cc8f0 commit 11d913c

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

_stable/client/basic.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,78 @@ println!("Response status: {}", res.status());
173173
# fn main() {}
174174
```
175175

176+
## POST
177+
Now that we've seen how to make a GET request, let's look at how to make a POST request. This is useful when you need to send data to the server, such as when submitting a form or uploading a file.
178+
179+
To make a POST request, we'll need to change a few things from our GET request:
180+
181+
1. We'll set the method to POST.
182+
2. We'll need to provide a request body.
183+
3. We'll need to specify the type of data in our body by adding a `hyper::header::CONTENT_TYPE` header.
184+
185+
For the body, we have a couple of options. We can use a simple string, a JSON string, or we can use raw bytes. Let's look at all three:
186+
187+
```rust
188+
# extern crate http_body_util;
189+
# extern crate hyper;
190+
# extern crate hyper_util;
191+
# extern crate tokio;
192+
# use http_body_util::Empty;
193+
# use hyper::body::Bytes;
194+
# use hyper::Request;
195+
# use hyper_util::rt::TokioIo;
196+
# use tokio::net::TcpStream;
197+
# async fn run() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
198+
# let url = "http://httpbin.org/ip".parse::<hyper::Uri>()?;
199+
# let host = url.host().expect("uri has no host");
200+
# let port = url.port_u16().unwrap_or(80);
201+
# let addr = format!("{}:{}", host, port);
202+
# let stream = TcpStream::connect(addr).await?;
203+
# let io = TokioIo::new(stream);
204+
# let (mut sender, conn) = hyper::client::conn::http1::handshake(io).await?;
205+
# tokio::task::spawn(async move {
206+
# if let Err(err) = conn.await {
207+
# println!("Connection failed: {:?}", err);
208+
# }
209+
# });
210+
211+
// The authority of our URL will be the hostname of the httpbin remote
212+
let authority = url.authority().unwrap().clone();
213+
214+
// For plain text
215+
let req_body = Full::<Bytes>::from("Some plain text as a body.");
216+
let req = Request::builder()
217+
.method(hyper::Method::POST)
218+
.header(hyper::header::HOST, authority.as_str())
219+
.header(hyper::header::CONTENT_TYPE, "text/plain")
220+
.body(req_body)?;
221+
222+
// For binary data
223+
let binary_data = vec![0u8; 128]; // Example binary data
224+
let req_body = Full::<Bytes>::from(binary_data);
225+
let req = Request::builder()
226+
.method(hyper::Method::POST)
227+
.header(hyper::header::HOST, authority.as_str())
228+
.header(hyper::header::CONTENT_TYPE, "application/octet-stream")
229+
.body(req_body)?;
230+
231+
// For JSON data (as previously mentioned)
232+
let json_data = r#"{"key": "value"}"#;
233+
let req_body = Full::<Bytes>::from(json_data);
234+
let req = Request::builder()
235+
.method(hyper::Method::POST)
236+
.header(hyper::header::HOST, authority.as_str())
237+
.header(hyper::header::CONTENT_TYPE, "application/json")
238+
.body(req_body)?;
239+
240+
let res = sender.send_request(req).await?;
241+
242+
println!("Response status: {}", res.status());
243+
# Ok(())
244+
# }
245+
# fn main() {}
246+
```
247+
176248
## Response bodies
177249

178250
We know that sending a GET `Request` to `httpbin.org/ip` will return our IP address in

0 commit comments

Comments
 (0)