Add support for application/x-www-form-urlencoded

This commit is contained in:
bbx0
2020-04-10 22:51:45 +02:00
committed by Martin Algesten
parent 92b4e7ec2c
commit 3bedf9ab69

View File

@@ -1,9 +1,10 @@
use std::borrow::Borrow;
use std::io::Read; use std::io::Read;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use qstring::QString; use qstring::QString;
use url::Url; use url::{form_urlencoded, Url};
use crate::agent::{self, Agent, AgentState}; use crate::agent::{self, Agent, AgentState};
use crate::body::Payload; use crate::body::Payload;
@@ -181,6 +182,37 @@ impl Request {
self.do_call(Payload::Text(text, charset)) 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<I, K, V>(&mut self, pairs: I) -> Response
where
I: IntoIterator,
I::Item: Borrow<(K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
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. /// Send data from a reader.
/// ///
/// The `Content-Length` header is not set because we can't know the length of the reader. /// The `Content-Length` header is not set because we can't know the length of the reader.