Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ResponseBuilder::send_form helper #859

Merged
merged 3 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ enum Source<'a> {
Owned(String),
}

fn enc(i: &str) -> Cow<str> {
pub fn url_enc(i: &str) -> Cow<str> {
utf8_percent_encode(i, percent_encoding::NON_ALPHANUMERIC).into()
}

impl<'a> QueryParam<'a> {
pub fn new_key_value(param: &str, value: &str) -> QueryParam<'static> {
let s = format!("{}={}", enc(param), enc(value));
let s = format!("{}={}", url_enc(param), url_enc(value));
QueryParam {
source: Source::Owned(s),
}
Expand Down
64 changes: 62 additions & 2 deletions src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ use http::{HeaderName, HeaderValue, Method, Request, Response, Uri, Version};

use crate::body::Body;
use crate::config::{Config, ConfigBuilder, RequestLevelConfig, RequestScope};
use crate::query::url_enc;
use crate::query::{parse_query_params, QueryParam};
use crate::send_body::AsSendBody;
use crate::util::private::Private;
use crate::util::HeaderMapExt;
use crate::util::UriExt;
use crate::{Agent, Error, SendBody};

Expand Down Expand Up @@ -323,12 +325,62 @@ impl RequestBuilder<WithBody> {
self.send(&[])
}

/// Send form encoded data.
///
/// Constructs a [form submission] with the content-type header
/// `application/x-www-form-urlencoded`. Keys and values will be URL encoded.
///
/// ```
/// let form = [
/// ("name", "martin"),
/// ("favorite_bird", "blue-footed booby"),
/// ];
///
/// let response = ureq::post("http://httpbin.org/post")
/// .send_form(form)?;
/// # Ok::<_, ureq::Error>(())
/// ```
///
/// [form submission]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST#url-encoded_form_submission
pub fn send_form<I, K, V>(self, iter: I) -> Result<Response<Body>, Error>
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
let iter = iter.into_iter();

// TODO(martin): can we calculate a size hint for capacity here?
let mut body = String::new();

for (k, v) in iter {
if !body.is_empty() {
body.push('&');
}
body.push_str(&url_enc(k.as_ref()));
body.push('=');
body.push_str(&url_enc(v.as_ref()));
}

let mut request = self.builder.body(())?;

if !request.headers().has_content_type() {
request.headers_mut().append(
http::header::CONTENT_TYPE,
HeaderValue::from_static("application/x-www-form-urlencoded"),
);
}

do_call(self.agent, request, self.query_extra, body.as_body())
}

/// Send body data as JSON.
///
/// Requires the **json** feature.
///
/// The data typically derives [`Serialize`](serde::Serialize) and is converted
/// to a string before sending (does allocate).
/// to a string before sending (does allocate). Will set the content-type header
/// `application/json`.
///
/// ```
/// use serde::Serialize;
Expand All @@ -348,8 +400,16 @@ impl RequestBuilder<WithBody> {
/// ```
#[cfg(feature = "json")]
pub fn send_json(self, data: impl serde::ser::Serialize) -> Result<Response<Body>, Error> {
let request = self.builder.body(())?;
let mut request = self.builder.body(())?;
let body = SendBody::from_json(&data)?;

if !request.headers().has_content_type() {
request.headers_mut().append(
http::header::CONTENT_TYPE,
HeaderValue::from_static("application/json; charset=utf-8"),
);
}

do_call(self.agent, request, self.query_extra, body)
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ pub(crate) trait HeaderMapExt {
self.is_chunked() || self.content_length().is_some()
}
fn has_accept(&self) -> bool;
fn has_content_type(&self) -> bool;
}

impl HeaderMapExt for HeaderMap {
Expand Down Expand Up @@ -357,4 +358,8 @@ impl HeaderMapExt for HeaderMap {
fn has_accept(&self) -> bool {
self.contains_key("accept")
}

fn has_content_type(&self) -> bool {
self.contains_key("content-type")
}
}
Loading