From 513ce0b08d51b75d73a98d6087cd329ee95ba09c Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Sat, 9 Mar 2019 17:42:35 -0800 Subject: [PATCH] add json and form client request's method --- src/client/request.rs | 44 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/client/request.rs b/src/client/request.rs index 7e971756d..efae5b94e 100644 --- a/src/client/request.rs +++ b/src/client/request.rs @@ -7,6 +7,8 @@ use bytes::{BufMut, Bytes, BytesMut}; use cookie::{Cookie, CookieJar}; use futures::{Future, Stream}; use percent_encoding::{percent_encode, USERINFO_ENCODE_SET}; +use serde::Serialize; +use serde_json; use crate::body::{BodyStream, MessageBody}; use crate::error::Error; @@ -558,6 +560,48 @@ impl ClientRequestBuilder { Ok(ClientRequest { head, body }) } + /// Set a JSON body and generate `ClientRequest` + /// + /// `ClientRequestBuilder` can not be used after this call. + pub fn json( + &mut self, + value: T, + ) -> Result, Error> { + let body = serde_json::to_string(&value)?; + + let contains = if let Some(head) = parts(&mut self.head, &self.err) { + head.headers.contains_key(header::CONTENT_TYPE) + } else { + true + }; + if !contains { + self.header(header::CONTENT_TYPE, "application/json"); + } + + Ok(self.body(body)?) + } + + /// Set a urlencoded body and generate `ClientRequest` + /// + /// `ClientRequestBuilder` can not be used after this call. + pub fn form( + &mut self, + value: T, + ) -> Result, Error> { + let body = serde_urlencoded::to_string(&value)?; + + let contains = if let Some(head) = parts(&mut self.head, &self.err) { + head.headers.contains_key(header::CONTENT_TYPE) + } else { + true + }; + if !contains { + self.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); + } + + Ok(self.body(body)?) + } + /// Set an streaming body and generate `ClientRequest`. /// /// `ClientRequestBuilder` can not be used after this call.