diff --git a/src/request.rs b/src/request.rs index 8422b15..151f754 100644 --- a/src/request.rs +++ b/src/request.rs @@ -1,9 +1,10 @@ +use std::borrow::Borrow; use std::io::Read; use std::sync::{Arc, Mutex}; use lazy_static::lazy_static; use qstring::QString; -use url::Url; +use url::{form_urlencoded, Url}; use crate::agent::{self, Agent, AgentState}; use crate::body::Payload; @@ -181,6 +182,37 @@ impl Request { self.do_call(Payload::Text(text, charset)) } + /// Send a sequence of (key, value) pairs as form-urlencoded data. + /// + /// The `Content-Type` header is implicitly set to application/x-www-form-urlencoded. + /// The `Content-Length` header is implicitly set to the length of the serialized value. + /// + /// ``` + /// #[macro_use] + /// extern crate ureq; + /// + /// fn main() { + /// let r = ureq::post("/my_page") + /// .send_form(&[("foo", "bar"),("foo2", "bar2")]); + /// println!("{:?}", r); + /// } + /// ``` + pub fn send_form(&mut self, pairs: I) -> Response + where + I: IntoIterator, + I::Item: Borrow<(K, V)>, + K: AsRef, + V: AsRef, + { + if self.header("Content-Type").is_none() { + self.set("Content-Type", "application/x-www-form-urlencoded"); + } + let encoded = form_urlencoded::Serializer::new(String::new()) + .extend_pairs(pairs) + .finish(); + self.do_call(Payload::Bytes(encoded.into_bytes())) + } + /// Send data from a reader. /// /// The `Content-Length` header is not set because we can't know the length of the reader.