@@ -18,11 +18,11 @@ error_chain! {
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut core = tokio_core::reactor::Core::new().unwrap();
|
||||
let client = Client::new(&core.handle()).unwrap();
|
||||
fn run() -> Result<()> {
|
||||
let mut core = tokio_core::reactor::Core::new()?;
|
||||
let client = Client::new(&core.handle());
|
||||
|
||||
let work = client.get("https://hyper.rs").unwrap()
|
||||
let work = client.get("https://hyper.rs")
|
||||
.send()
|
||||
.map_err(|e| Error::from(e))
|
||||
.and_then(|mut res| {
|
||||
@@ -36,5 +36,8 @@ fn main() {
|
||||
io::copy(&mut body, &mut io::stdout()).map_err(Into::into)
|
||||
});
|
||||
|
||||
core.run(work).unwrap();
|
||||
core.run(work)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
quick_main!(run);
|
||||
|
||||
@@ -31,6 +31,7 @@ pub struct Client {
|
||||
/// A `ClientBuilder` can be used to create a `Client` with custom configuration:
|
||||
pub struct ClientBuilder {
|
||||
config: Option<Config>,
|
||||
err: Option<::Error>,
|
||||
}
|
||||
|
||||
struct Config {
|
||||
@@ -45,23 +46,25 @@ struct Config {
|
||||
|
||||
impl ClientBuilder {
|
||||
/// Constructs a new `ClientBuilder`
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails if native TLS backend cannot be created.
|
||||
pub fn new() -> ::Result<ClientBuilder> {
|
||||
let tls_connector_builder = try_!(TlsConnector::builder());
|
||||
Ok(ClientBuilder {
|
||||
config: Some(Config {
|
||||
gzip: true,
|
||||
hostname_verification: true,
|
||||
proxies: Vec::new(),
|
||||
redirect_policy: RedirectPolicy::default(),
|
||||
referer: true,
|
||||
timeout: None,
|
||||
tls: tls_connector_builder,
|
||||
})
|
||||
})
|
||||
pub fn new() -> ClientBuilder {
|
||||
match TlsConnector::builder() {
|
||||
Ok(tls_connector_builder) => ClientBuilder {
|
||||
config: Some(Config {
|
||||
gzip: true,
|
||||
hostname_verification: true,
|
||||
proxies: Vec::new(),
|
||||
redirect_policy: RedirectPolicy::default(),
|
||||
referer: true,
|
||||
timeout: None,
|
||||
tls: tls_connector_builder,
|
||||
}),
|
||||
err: None,
|
||||
},
|
||||
Err(e) => ClientBuilder {
|
||||
config: None,
|
||||
err: Some(::error::from(e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `Client` that uses this `ClientBuilder` configuration.
|
||||
@@ -75,7 +78,12 @@ impl ClientBuilder {
|
||||
/// This method consumes the internal state of the builder.
|
||||
/// Trying to use this builder again after calling `build` will panic.
|
||||
pub fn build(&mut self, handle: &Handle) -> ::Result<Client> {
|
||||
let config = self.take_config();
|
||||
if let Some(err) = self.err.take() {
|
||||
return Err(err);
|
||||
}
|
||||
let config = self.config
|
||||
.take()
|
||||
.expect("ClientBuilder cannot be reused after building a Client");
|
||||
|
||||
let tls = try_!(config.tls.build());
|
||||
|
||||
@@ -105,28 +113,25 @@ impl ClientBuilder {
|
||||
///
|
||||
/// This can be used to connect to a server that has a self-signed
|
||||
/// certificate for example.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails if adding root certificate was unsuccessful.
|
||||
pub fn add_root_certificate(&mut self, cert: Certificate) -> ::Result<&mut ClientBuilder> {
|
||||
let cert = ::tls::cert(cert);
|
||||
try_!(self.config_mut().tls.add_root_certificate(cert));
|
||||
Ok(self)
|
||||
pub fn add_root_certificate(&mut self, cert: Certificate) -> &mut ClientBuilder {
|
||||
if let Some(config) = config_mut(&mut self.config, &self.err) {
|
||||
let cert = ::tls::cert(cert);
|
||||
if let Err(e) = config.tls.add_root_certificate(cert) {
|
||||
self.err = Some(::error::from(e));
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the identity to be used for client certificate authentication.
|
||||
///
|
||||
/// This can be used in mutual authentication scenarios to identify to a server
|
||||
/// with a Pkcs12 archive containing a certificate and private key for example.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails if adding client identity was unsuccessful.
|
||||
pub fn identity(&mut self, identity: Identity) -> ::Result<&mut ClientBuilder> {
|
||||
let pkcs12 = ::tls::pkcs12(identity);
|
||||
try_!(self.config_mut().tls.identity(pkcs12));
|
||||
Ok(self)
|
||||
pub fn identity(&mut self, identity: Identity) -> &mut ClientBuilder {
|
||||
if let Some(config) = config_mut(&mut self.config, &self.err) {
|
||||
let pkcs12 = ::tls::pkcs12(identity);
|
||||
if let Err(e) = config.tls.identity(pkcs12) {
|
||||
self.err = Some(::error::from(e));
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Disable hostname verification.
|
||||
@@ -139,14 +144,19 @@ impl ClientBuilder {
|
||||
/// significant vulnerability to man-in-the-middle attacks.
|
||||
#[inline]
|
||||
pub fn danger_disable_hostname_verification(&mut self) -> &mut ClientBuilder {
|
||||
self.config_mut().hostname_verification = false;
|
||||
|
||||
if let Some(config) = config_mut(&mut self.config, &self.err) {
|
||||
config.hostname_verification = false;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Enable hostname verification.
|
||||
#[inline]
|
||||
pub fn enable_hostname_verification(&mut self) -> &mut ClientBuilder {
|
||||
self.config_mut().hostname_verification = true;
|
||||
if let Some(config) = config_mut(&mut self.config, &self.err) {
|
||||
config.hostname_verification = true;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -155,14 +165,18 @@ impl ClientBuilder {
|
||||
/// Default is enabled.
|
||||
#[inline]
|
||||
pub fn gzip(&mut self, enable: bool) -> &mut ClientBuilder {
|
||||
self.config_mut().gzip = enable;
|
||||
if let Some(config) = config_mut(&mut self.config, &self.err) {
|
||||
config.gzip = enable;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a `Proxy` to the list of proxies the `Client` will use.
|
||||
#[inline]
|
||||
pub fn proxy(&mut self, proxy: Proxy) -> &mut ClientBuilder {
|
||||
self.config_mut().proxies.push(proxy);
|
||||
if let Some(config) = config_mut(&mut self.config, &self.err) {
|
||||
config.proxies.push(proxy);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -171,7 +185,9 @@ impl ClientBuilder {
|
||||
/// Default will follow redirects up to a maximum of 10.
|
||||
#[inline]
|
||||
pub fn redirect(&mut self, policy: RedirectPolicy) -> &mut ClientBuilder {
|
||||
self.config_mut().redirect_policy = policy;
|
||||
if let Some(config) = config_mut(&mut self.config, &self.err) {
|
||||
config.redirect_policy = policy;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -180,28 +196,27 @@ impl ClientBuilder {
|
||||
/// Default is `true`.
|
||||
#[inline]
|
||||
pub fn referer(&mut self, enable: bool) -> &mut ClientBuilder {
|
||||
self.config_mut().referer = enable;
|
||||
if let Some(config) = config_mut(&mut self.config, &self.err) {
|
||||
config.referer = enable;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Set a timeout for both the read and write operations of a client.
|
||||
#[inline]
|
||||
pub fn timeout(&mut self, timeout: Duration) -> &mut ClientBuilder {
|
||||
self.config_mut().timeout = Some(timeout);
|
||||
if let Some(config) = config_mut(&mut self.config, &self.err) {
|
||||
config.timeout = Some(timeout);
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// private
|
||||
fn config_mut(&mut self) -> &mut Config {
|
||||
self.config
|
||||
.as_mut()
|
||||
.expect("ClientBuilder cannot be reused after building a Client")
|
||||
}
|
||||
|
||||
fn take_config(&mut self) -> Config {
|
||||
self.config
|
||||
.take()
|
||||
.expect("ClientBuilder cannot be reused after building a Client")
|
||||
fn config_mut<'a>(config: &'a mut Option<Config>, err: &Option<::Error>) -> Option<&'a mut Config> {
|
||||
if err.is_some() {
|
||||
None
|
||||
} else {
|
||||
config.as_mut()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,21 +231,21 @@ fn create_hyper_client(tls: TlsConnector, proxies: Arc<Vec<Proxy>>, handle: &Han
|
||||
impl Client {
|
||||
/// Constructs a new `Client`.
|
||||
///
|
||||
/// # Errors
|
||||
/// # Panics
|
||||
///
|
||||
/// This method fails if native TLS backend cannot be created or initialized.
|
||||
/// This method panics if native TLS backend cannot be created or
|
||||
/// initialized. Use `Client::builder()` if you wish to handle the failure
|
||||
/// as an `Error` instead of panicking.
|
||||
#[inline]
|
||||
pub fn new(handle: &Handle) -> ::Result<Client> {
|
||||
ClientBuilder::new()?.build(handle)
|
||||
pub fn new(handle: &Handle) -> Client {
|
||||
ClientBuilder::new()
|
||||
.build(handle)
|
||||
.expect("TLS failed to initialize")
|
||||
}
|
||||
|
||||
/// Creates a `ClientBuilder` to configure a `Client`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails if native TLS backend cannot be created.
|
||||
#[inline]
|
||||
pub fn builder() -> ::Result<ClientBuilder> {
|
||||
pub fn builder() -> ClientBuilder {
|
||||
ClientBuilder::new()
|
||||
}
|
||||
|
||||
@@ -239,7 +254,7 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn get<U: IntoUrl>(&self, url: U) -> ::Result<RequestBuilder> {
|
||||
pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
|
||||
self.request(Method::Get, url)
|
||||
}
|
||||
|
||||
@@ -248,7 +263,7 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn post<U: IntoUrl>(&self, url: U) -> ::Result<RequestBuilder> {
|
||||
pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder {
|
||||
self.request(Method::Post, url)
|
||||
}
|
||||
|
||||
@@ -257,7 +272,7 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn put<U: IntoUrl>(&self, url: U) -> ::Result<RequestBuilder> {
|
||||
pub fn put<U: IntoUrl>(&self, url: U) -> RequestBuilder {
|
||||
self.request(Method::Put, url)
|
||||
}
|
||||
|
||||
@@ -266,7 +281,7 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn patch<U: IntoUrl>(&self, url: U) -> ::Result<RequestBuilder> {
|
||||
pub fn patch<U: IntoUrl>(&self, url: U) -> RequestBuilder {
|
||||
self.request(Method::Patch, url)
|
||||
}
|
||||
|
||||
@@ -275,7 +290,7 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn delete<U: IntoUrl>(&self, url: U) -> ::Result<RequestBuilder> {
|
||||
pub fn delete<U: IntoUrl>(&self, url: U) -> RequestBuilder {
|
||||
self.request(Method::Delete, url)
|
||||
}
|
||||
|
||||
@@ -284,7 +299,7 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn head<U: IntoUrl>(&self, url: U) -> ::Result<RequestBuilder> {
|
||||
pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder {
|
||||
self.request(Method::Head, url)
|
||||
}
|
||||
|
||||
@@ -296,9 +311,12 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> ::Result<RequestBuilder> {
|
||||
let url = try_!(url.into_url());
|
||||
Ok(request::builder(self.clone(), Request::new(method, url)))
|
||||
pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
|
||||
let req = match url.into_url() {
|
||||
Ok(url) => Ok(Request::new(method, url)),
|
||||
Err(err) => Err(::error::from(err)),
|
||||
};
|
||||
request::builder(self.clone(), req)
|
||||
}
|
||||
|
||||
/// Executes a `Request`.
|
||||
@@ -357,16 +375,18 @@ impl Client {
|
||||
let in_flight = self.inner.hyper.request(req);
|
||||
|
||||
Pending {
|
||||
method: method,
|
||||
url: url,
|
||||
headers: headers,
|
||||
body: body,
|
||||
inner: PendingInner::Request(PendingRequest {
|
||||
method: method,
|
||||
url: url,
|
||||
headers: headers,
|
||||
body: body,
|
||||
|
||||
urls: Vec::new(),
|
||||
urls: Vec::new(),
|
||||
|
||||
client: self.inner.clone(),
|
||||
client: self.inner.clone(),
|
||||
|
||||
in_flight: in_flight,
|
||||
in_flight: in_flight,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -397,6 +417,15 @@ struct ClientRef {
|
||||
}
|
||||
|
||||
pub struct Pending {
|
||||
inner: PendingInner,
|
||||
}
|
||||
|
||||
enum PendingInner {
|
||||
Request(PendingRequest),
|
||||
Error(Option<::Error>),
|
||||
}
|
||||
|
||||
pub struct PendingRequest {
|
||||
method: Method,
|
||||
url: Url,
|
||||
headers: Headers,
|
||||
@@ -409,10 +438,23 @@ pub struct Pending {
|
||||
in_flight: FutureResponse,
|
||||
}
|
||||
|
||||
|
||||
impl Future for Pending {
|
||||
type Item = Response;
|
||||
type Error = ::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.inner {
|
||||
PendingInner::Request(ref mut req) => req.poll(),
|
||||
PendingInner::Error(ref mut err) => Err(err.take().expect("Pending error polled more than once")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Future for PendingRequest {
|
||||
type Item = Response;
|
||||
type Error = ::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
loop {
|
||||
let res = match try_!(self.in_flight.poll(), &self.url) {
|
||||
@@ -497,10 +539,19 @@ impl Future for Pending {
|
||||
|
||||
impl fmt::Debug for Pending {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.debug_struct("Pending")
|
||||
.field("method", &self.method)
|
||||
.field("url", &self.url)
|
||||
.finish()
|
||||
match self.inner {
|
||||
PendingInner::Request(ref req) => {
|
||||
f.debug_struct("Pending")
|
||||
.field("method", &req.method)
|
||||
.field("url", &req.url)
|
||||
.finish()
|
||||
},
|
||||
PendingInner::Error(ref err) => {
|
||||
f.debug_struct("Pending")
|
||||
.field("error", err)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,5 +571,11 @@ fn make_referer(next: &Url, previous: &Url) -> Option<Referer> {
|
||||
|
||||
pub fn take_builder(builder: &mut ClientBuilder) -> ClientBuilder {
|
||||
use std::mem;
|
||||
mem::replace(builder, ClientBuilder { config: None })
|
||||
mem::replace(builder, ClientBuilder { config: None, err: None })
|
||||
}
|
||||
|
||||
pub fn pending_err(err: ::Error) -> Pending {
|
||||
Pending {
|
||||
inner: PendingInner::Error(Some(err)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use serde_json;
|
||||
use serde_urlencoded;
|
||||
|
||||
use super::body::{self, Body};
|
||||
use super::client::{Client, Pending};
|
||||
use super::client::{Client, Pending, pending_err};
|
||||
use header::{ContentType, Headers};
|
||||
use {Method, Url};
|
||||
|
||||
@@ -21,6 +21,7 @@ pub struct Request {
|
||||
pub struct RequestBuilder {
|
||||
client: Client,
|
||||
request: Option<Request>,
|
||||
err: Option<::Error>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
@@ -90,14 +91,18 @@ impl RequestBuilder {
|
||||
where
|
||||
H: ::header::Header,
|
||||
{
|
||||
self.request_mut().headers.set(header);
|
||||
if let Some(req) = request_mut(&mut self.request, &self.err) {
|
||||
req.headers_mut().set(header);
|
||||
}
|
||||
self
|
||||
}
|
||||
/// Add a set of Headers to the existing ones on this Request.
|
||||
///
|
||||
/// The headers will be merged in to any already set.
|
||||
pub fn headers(&mut self, headers: ::header::Headers) -> &mut RequestBuilder {
|
||||
self.request_mut().headers.extend(headers.iter());
|
||||
if let Some(req) = request_mut(&mut self.request, &self.err) {
|
||||
req.headers_mut().extend(headers.iter());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -115,20 +120,24 @@ impl RequestBuilder {
|
||||
|
||||
/// Set the request body.
|
||||
pub fn body<T: Into<Body>>(&mut self, body: T) -> &mut RequestBuilder {
|
||||
self.request_mut().body = Some(body.into());
|
||||
if let Some(req) = request_mut(&mut self.request, &self.err) {
|
||||
*req.body_mut() = Some(body.into());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Send a form body.
|
||||
pub fn form<T: Serialize>(&mut self, form: &T) -> ::Result<&mut RequestBuilder> {
|
||||
{
|
||||
// check request_mut() before running serde
|
||||
let mut req = self.request_mut();
|
||||
let body = try_!(serde_urlencoded::to_string(form));
|
||||
req.headers.set(ContentType::form_url_encoded());
|
||||
req.body = Some(body::reusable(body.into()));
|
||||
pub fn form<T: Serialize>(&mut self, form: &T) -> &mut RequestBuilder {
|
||||
if let Some(req) = request_mut(&mut self.request, &self.err) {
|
||||
match serde_urlencoded::to_string(form) {
|
||||
Ok(body) => {
|
||||
req.headers_mut().set(ContentType::form_url_encoded());
|
||||
*req.body_mut() = Some(body.into());
|
||||
},
|
||||
Err(err) => self.err = Some(::error::from(err)),
|
||||
}
|
||||
}
|
||||
Ok(self)
|
||||
self
|
||||
}
|
||||
|
||||
/// Send a JSON body.
|
||||
@@ -137,15 +146,17 @@ impl RequestBuilder {
|
||||
///
|
||||
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
|
||||
/// fail, or if `T` contains a map with non-string keys.
|
||||
pub fn json<T: Serialize>(&mut self, json: &T) -> ::Result<&mut RequestBuilder> {
|
||||
{
|
||||
// check request_mut() before running serde
|
||||
let mut req = self.request_mut();
|
||||
let body = try_!(serde_json::to_vec(json));
|
||||
req.headers.set(ContentType::json());
|
||||
req.body = Some(body::reusable(body.into()));
|
||||
pub fn json<T: Serialize>(&mut self, json: &T) -> &mut RequestBuilder {
|
||||
if let Some(req) = request_mut(&mut self.request, &self.err) {
|
||||
match serde_json::to_vec(json) {
|
||||
Ok(body) => {
|
||||
req.headers_mut().set(ContentType::json());
|
||||
*req.body_mut() = Some(body.into());
|
||||
},
|
||||
Err(err) => self.err = Some(::error::from(err)),
|
||||
}
|
||||
}
|
||||
Ok(self)
|
||||
self
|
||||
}
|
||||
|
||||
/// Build a `Request`, which can be inspected, modified and executed with
|
||||
@@ -155,10 +166,14 @@ impl RequestBuilder {
|
||||
///
|
||||
/// This method consumes builder internal state. It panics on an attempt to
|
||||
/// reuse already consumed builder.
|
||||
pub fn build(&mut self) -> Request {
|
||||
self.request
|
||||
.take()
|
||||
.expect("RequestBuilder cannot be reused after builder a Request")
|
||||
pub fn build(&mut self) -> ::Result<Request> {
|
||||
if let Some(err) = self.err.take() {
|
||||
Err(err)
|
||||
} else {
|
||||
Ok(self.request
|
||||
.take()
|
||||
.expect("RequestBuilder cannot be reused after builder a Request"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs the Request and sends it the target URL, returning a Response.
|
||||
@@ -168,16 +183,18 @@ impl RequestBuilder {
|
||||
/// This method fails if there was an error while sending request,
|
||||
/// redirect loop was detected or redirect limit was exhausted.
|
||||
pub fn send(&mut self) -> Pending {
|
||||
let request = self.build();
|
||||
self.client.execute(request)
|
||||
match self.build() {
|
||||
Ok(req) => self.client.execute(req),
|
||||
Err(err) => pending_err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// private
|
||||
|
||||
fn request_mut(&mut self) -> &mut Request {
|
||||
self.request
|
||||
.as_mut()
|
||||
.expect("RequestBuilder cannot be reused after builder a Request")
|
||||
fn request_mut<'a>(req: &'a mut Option<Request>, err: &Option<::Error>) -> Option<&'a mut Request> {
|
||||
if err.is_some() {
|
||||
None
|
||||
} else {
|
||||
req.as_mut()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,10 +227,18 @@ fn fmt_request_fields<'a, 'b>(f: &'a mut fmt::DebugStruct<'a, 'b>, req: &Request
|
||||
// pub(crate)
|
||||
|
||||
#[inline]
|
||||
pub fn builder(client: Client, req: Request) -> RequestBuilder {
|
||||
RequestBuilder {
|
||||
client: client,
|
||||
request: Some(req),
|
||||
pub fn builder(client: Client, req: ::Result<Request>) -> RequestBuilder {
|
||||
match req {
|
||||
Ok(req) => RequestBuilder {
|
||||
client: client,
|
||||
request: Some(req),
|
||||
err: None,
|
||||
},
|
||||
Err(err) => RequestBuilder {
|
||||
client: client,
|
||||
request: None,
|
||||
err: Some(err)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ use {async_impl, Certificate, Identity, Method, IntoUrl, Proxy, RedirectPolicy,
|
||||
/// are set to what is usually the most commonly desired value.
|
||||
///
|
||||
/// The `Client` holds a connection pool internally, so it is advised that
|
||||
/// you create one and reuse it.
|
||||
/// you create one and **reuse** it.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
@@ -24,8 +24,8 @@ use {async_impl, Certificate, Identity, Method, IntoUrl, Proxy, RedirectPolicy,
|
||||
/// # use reqwest::{Error, Client};
|
||||
/// #
|
||||
/// # fn run() -> Result<(), Error> {
|
||||
/// let client = Client::new()?;
|
||||
/// let resp = client.get("http://httpbin.org/")?.send()?;
|
||||
/// let client = Client::new();
|
||||
/// let resp = client.get("http://httpbin.org/").send()?;
|
||||
/// # drop(resp);
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
@@ -44,7 +44,7 @@ pub struct Client {
|
||||
/// # fn run() -> Result<(), reqwest::Error> {
|
||||
/// use std::time::Duration;
|
||||
///
|
||||
/// let client = reqwest::Client::builder()?
|
||||
/// let client = reqwest::Client::builder()
|
||||
/// .gzip(true)
|
||||
/// .timeout(Duration::from_secs(10))
|
||||
/// .build()?;
|
||||
@@ -58,15 +58,11 @@ pub struct ClientBuilder {
|
||||
|
||||
impl ClientBuilder {
|
||||
/// Constructs a new `ClientBuilder`
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails if native TLS backend cannot be created.
|
||||
pub fn new() -> ::Result<ClientBuilder> {
|
||||
async_impl::ClientBuilder::new().map(|builder| ClientBuilder {
|
||||
inner: builder,
|
||||
pub fn new() -> ClientBuilder {
|
||||
ClientBuilder {
|
||||
inner: async_impl::ClientBuilder::new(),
|
||||
timeout: Timeout::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `Client` that uses this `ClientBuilder` configuration.
|
||||
@@ -103,8 +99,8 @@ impl ClientBuilder {
|
||||
/// let cert = reqwest::Certificate::from_der(&buf)?;
|
||||
///
|
||||
/// // get a client builder
|
||||
/// let client = reqwest::ClientBuilder::new()?
|
||||
/// .add_root_certificate(cert)?
|
||||
/// let client = reqwest::Client::builder()
|
||||
/// .add_root_certificate(cert)
|
||||
/// .build()?;
|
||||
/// # drop(client);
|
||||
/// # Ok(())
|
||||
@@ -114,17 +110,15 @@ impl ClientBuilder {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails if adding root certificate was unsuccessful.
|
||||
pub fn add_root_certificate(&mut self, cert: Certificate) -> ::Result<&mut ClientBuilder> {
|
||||
self.inner.add_root_certificate(cert)?;
|
||||
Ok(self)
|
||||
pub fn add_root_certificate(&mut self, cert: Certificate) -> &mut ClientBuilder {
|
||||
self.inner.add_root_certificate(cert);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the identity to be used for client certificate authentication.
|
||||
///
|
||||
/// This can be used in mutual authentication scenarios to identify to a server
|
||||
/// with a PKCS#12 archive containing a certificate and private key for example.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use std::fs::File;
|
||||
/// # use std::io::Read;
|
||||
@@ -137,20 +131,16 @@ impl ClientBuilder {
|
||||
/// let pkcs12 = reqwest::Identity::from_pkcs12_der(&buf, "my-privkey-password")?;
|
||||
///
|
||||
/// // get a client builder
|
||||
/// let client = reqwest::ClientBuilder::new()?
|
||||
/// .identity(pkcs12)?
|
||||
/// let client = reqwest::Client::builder()
|
||||
/// .identity(pkcs12)
|
||||
/// .build()?;
|
||||
/// # drop(client);
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails if adding client identity was unsuccessful.
|
||||
pub fn identity(&mut self, identity: Identity) -> ::Result<&mut ClientBuilder> {
|
||||
self.inner.identity(identity)?;
|
||||
Ok(self)
|
||||
pub fn identity(&mut self, identity: Identity) -> &mut ClientBuilder {
|
||||
self.inner.identity(identity);
|
||||
self
|
||||
}
|
||||
|
||||
|
||||
@@ -229,21 +219,21 @@ impl ClientBuilder {
|
||||
impl Client {
|
||||
/// Constructs a new `Client`.
|
||||
///
|
||||
/// # Errors
|
||||
/// # Panic
|
||||
///
|
||||
/// This method fails if native TLS backend cannot be created or initialized.
|
||||
/// This method panics if native TLS backend cannot be created or
|
||||
/// initialized. Use `Client::builder()` if you wish to handle the failure
|
||||
/// as an `Error` instead of panicking.
|
||||
#[inline]
|
||||
pub fn new() -> ::Result<Client> {
|
||||
ClientBuilder::new()?.build()
|
||||
pub fn new() -> Client {
|
||||
ClientBuilder::new()
|
||||
.build()
|
||||
.expect("Client failed to initialize")
|
||||
}
|
||||
|
||||
/// Creates a `ClientBuilder` to configure a `Client`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails if native TLS backend cannot be created.
|
||||
#[inline]
|
||||
pub fn builder() -> ::Result<ClientBuilder> {
|
||||
pub fn builder() -> ClientBuilder {
|
||||
ClientBuilder::new()
|
||||
}
|
||||
|
||||
@@ -252,7 +242,7 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn get<U: IntoUrl>(&self, url: U) -> ::Result<RequestBuilder> {
|
||||
pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
|
||||
self.request(Method::Get, url)
|
||||
}
|
||||
|
||||
@@ -261,7 +251,7 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn post<U: IntoUrl>(&self, url: U) -> ::Result<RequestBuilder> {
|
||||
pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder {
|
||||
self.request(Method::Post, url)
|
||||
}
|
||||
|
||||
@@ -270,7 +260,7 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn put<U: IntoUrl>(&self, url: U) -> ::Result<RequestBuilder> {
|
||||
pub fn put<U: IntoUrl>(&self, url: U) -> RequestBuilder {
|
||||
self.request(Method::Put, url)
|
||||
}
|
||||
|
||||
@@ -279,7 +269,7 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn patch<U: IntoUrl>(&self, url: U) -> ::Result<RequestBuilder> {
|
||||
pub fn patch<U: IntoUrl>(&self, url: U) -> RequestBuilder {
|
||||
self.request(Method::Patch, url)
|
||||
}
|
||||
|
||||
@@ -288,7 +278,7 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn delete<U: IntoUrl>(&self, url: U) -> ::Result<RequestBuilder> {
|
||||
pub fn delete<U: IntoUrl>(&self, url: U) -> RequestBuilder {
|
||||
self.request(Method::Delete, url)
|
||||
}
|
||||
|
||||
@@ -297,7 +287,7 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn head<U: IntoUrl>(&self, url: U) -> ::Result<RequestBuilder> {
|
||||
pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder {
|
||||
self.request(Method::Head, url)
|
||||
}
|
||||
|
||||
@@ -309,9 +299,12 @@ impl Client {
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails whenever supplied `Url` cannot be parsed.
|
||||
pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> ::Result<RequestBuilder> {
|
||||
let url = try_!(url.into_url());
|
||||
Ok(request::builder(self.clone(), Request::new(method, url)))
|
||||
pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
|
||||
let req = match url.into_url() {
|
||||
Ok(url) => Ok(Request::new(method, url)),
|
||||
Err(err) => Err(::error::from(err)),
|
||||
};
|
||||
request::builder(self.clone(), req)
|
||||
}
|
||||
|
||||
/// Executes a `Request`.
|
||||
|
||||
20
src/lib.rs
20
src/lib.rs
@@ -58,8 +58,8 @@
|
||||
//! # use reqwest::Error;
|
||||
//! #
|
||||
//! # fn run() -> Result<(), Error> {
|
||||
//! let client = reqwest::Client::new()?;
|
||||
//! let res = client.post("http://httpbin.org/post")?
|
||||
//! let client = reqwest::Client::new();
|
||||
//! let res = client.post("http://httpbin.org/post")
|
||||
//! .body("the exact body that is sent")
|
||||
//! .send()?;
|
||||
//! # Ok(())
|
||||
@@ -80,9 +80,9 @@
|
||||
//! # fn run() -> Result<(), Error> {
|
||||
//! // This will POST a body of `foo=bar&baz=quux`
|
||||
//! let params = [("foo", "bar"), ("baz", "quux")];
|
||||
//! let client = reqwest::Client::new()?;
|
||||
//! let res = client.post("http://httpbin.org/post")?
|
||||
//! .form(¶ms)?
|
||||
//! let client = reqwest::Client::new();
|
||||
//! let res = client.post("http://httpbin.org/post")
|
||||
//! .form(¶ms)
|
||||
//! .send()?;
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
@@ -104,9 +104,9 @@
|
||||
//! map.insert("lang", "rust");
|
||||
//! map.insert("body", "json");
|
||||
//!
|
||||
//! let client = reqwest::Client::new()?;
|
||||
//! let res = client.post("http://httpbin.org/post")?
|
||||
//! .json(&map)?
|
||||
//! let client = reqwest::Client::new();
|
||||
//! let res = client.post("http://httpbin.org/post")
|
||||
//! .json(&map)
|
||||
//! .send()?;
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
@@ -228,8 +228,8 @@ pub mod unstable {
|
||||
/// - redirect loop was detected
|
||||
/// - redirect limit was exhausted
|
||||
pub fn get<T: IntoUrl>(url: T) -> ::Result<Response> {
|
||||
Client::new()?
|
||||
.get(url)?
|
||||
Client::new()
|
||||
.get(url)
|
||||
.send()
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ impl Proxy {
|
||||
/// ```
|
||||
/// # extern crate reqwest;
|
||||
/// # fn run() -> Result<(), Box<::std::error::Error>> {
|
||||
/// let client = reqwest::Client::builder()?
|
||||
/// let client = reqwest::Client::builder()
|
||||
/// .proxy(reqwest::Proxy::http("https://my.prox")?)
|
||||
/// .build()?;
|
||||
/// # Ok(())
|
||||
@@ -62,7 +62,7 @@ impl Proxy {
|
||||
/// ```
|
||||
/// # extern crate reqwest;
|
||||
/// # fn run() -> Result<(), Box<::std::error::Error>> {
|
||||
/// let client = reqwest::Client::builder()?
|
||||
/// let client = reqwest::Client::builder()
|
||||
/// .proxy(reqwest::Proxy::https("https://example.prox:4545")?)
|
||||
/// .build()?;
|
||||
/// # Ok(())
|
||||
@@ -81,7 +81,7 @@ impl Proxy {
|
||||
/// ```
|
||||
/// # extern crate reqwest;
|
||||
/// # fn run() -> Result<(), Box<::std::error::Error>> {
|
||||
/// let client = reqwest::Client::builder()?
|
||||
/// let client = reqwest::Client::builder()
|
||||
/// .proxy(reqwest::Proxy::all("http://pro.xy")?)
|
||||
/// .build()?;
|
||||
/// # Ok(())
|
||||
@@ -101,7 +101,7 @@ impl Proxy {
|
||||
/// # extern crate reqwest;
|
||||
/// # fn run() -> Result<(), Box<::std::error::Error>> {
|
||||
/// let target = reqwest::Url::parse("https://my.prox")?;
|
||||
/// let client = reqwest::Client::builder()?
|
||||
/// let client = reqwest::Client::builder()
|
||||
/// .proxy(reqwest::Proxy::custom(move |url| {
|
||||
/// if url.host_str() == Some("hyper.rs") {
|
||||
/// Some(target.clone())
|
||||
|
||||
@@ -74,7 +74,7 @@ impl RedirectPolicy {
|
||||
/// attempt.follow()
|
||||
/// }
|
||||
/// });
|
||||
/// let client = reqwest::Client::builder()?
|
||||
/// let client = reqwest::Client::builder()
|
||||
/// .redirect(custom)
|
||||
/// .build()?;
|
||||
/// # Ok(())
|
||||
|
||||
195
src/request.rs
195
src/request.rs
@@ -19,6 +19,7 @@ pub struct Request {
|
||||
pub struct RequestBuilder {
|
||||
client: Client,
|
||||
request: Option<Request>,
|
||||
err: Option<::Error>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
@@ -87,8 +88,8 @@ impl RequestBuilder {
|
||||
/// use reqwest::header::UserAgent;
|
||||
///
|
||||
/// # fn run() -> Result<(), Box<::std::error::Error>> {
|
||||
/// let client = reqwest::Client::new()?;
|
||||
/// let res = client.get("https://www.rust-lang.org")?
|
||||
/// let client = reqwest::Client::new();
|
||||
/// let res = client.get("https://www.rust-lang.org")
|
||||
/// .header(UserAgent::new("foo"))
|
||||
/// .send()?;
|
||||
/// # Ok(())
|
||||
@@ -98,7 +99,9 @@ impl RequestBuilder {
|
||||
where
|
||||
H: ::header::Header,
|
||||
{
|
||||
self.request_mut().headers_mut().set(header);
|
||||
if let Some(req) = request_mut(&mut self.request, &self.err) {
|
||||
req.headers_mut().set(header);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -119,8 +122,8 @@ impl RequestBuilder {
|
||||
///
|
||||
/// # fn run() -> Result<(), Box<::std::error::Error>> {
|
||||
/// let file = fs::File::open("much_beauty.png")?;
|
||||
/// let client = reqwest::Client::new()?;
|
||||
/// let res = client.post("http://httpbin.org/post")?
|
||||
/// let client = reqwest::Client::new();
|
||||
/// let res = client.post("http://httpbin.org/post")
|
||||
/// .headers(construct_headers())
|
||||
/// .body(file)
|
||||
/// .send()?;
|
||||
@@ -128,7 +131,9 @@ impl RequestBuilder {
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn headers(&mut self, headers: ::header::Headers) -> &mut RequestBuilder {
|
||||
self.request_mut().headers_mut().extend(headers.iter());
|
||||
if let Some(req) = request_mut(&mut self.request, &self.err) {
|
||||
req.headers_mut().extend(headers.iter());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -136,8 +141,8 @@ impl RequestBuilder {
|
||||
///
|
||||
/// ```rust
|
||||
/// # fn run() -> Result<(), Box<::std::error::Error>> {
|
||||
/// let client = reqwest::Client::new()?;
|
||||
/// let resp = client.delete("http://httpbin.org/delete")?
|
||||
/// let client = reqwest::Client::new();
|
||||
/// let resp = client.delete("http://httpbin.org/delete")
|
||||
/// .basic_auth("admin", Some("good password"))
|
||||
/// .send()?;
|
||||
/// # Ok(())
|
||||
@@ -162,8 +167,8 @@ impl RequestBuilder {
|
||||
///
|
||||
/// ```rust
|
||||
/// # fn run() -> Result<(), Box<::std::error::Error>> {
|
||||
/// let client = reqwest::Client::new()?;
|
||||
/// let res = client.post("http://httpbin.org/post")?
|
||||
/// let client = reqwest::Client::new();
|
||||
/// let res = client.post("http://httpbin.org/post")
|
||||
/// .body("from a &str!")
|
||||
/// .send()?;
|
||||
/// # Ok(())
|
||||
@@ -176,8 +181,8 @@ impl RequestBuilder {
|
||||
/// # use std::fs;
|
||||
/// # fn run() -> Result<(), Box<::std::error::Error>> {
|
||||
/// let file = fs::File::open("from_a_file.txt")?;
|
||||
/// let client = reqwest::Client::new()?;
|
||||
/// let res = client.post("http://httpbin.org/post")?
|
||||
/// let client = reqwest::Client::new();
|
||||
/// let res = client.post("http://httpbin.org/post")
|
||||
/// .body(file)
|
||||
/// .send()?;
|
||||
/// # Ok(())
|
||||
@@ -191,15 +196,17 @@ impl RequestBuilder {
|
||||
/// # fn run() -> Result<(), Box<::std::error::Error>> {
|
||||
/// // from bytes!
|
||||
/// let bytes: Vec<u8> = vec![1, 10, 100];
|
||||
/// let client = reqwest::Client::new()?;
|
||||
/// let res = client.post("http://httpbin.org/post")?
|
||||
/// let client = reqwest::Client::new();
|
||||
/// let res = client.post("http://httpbin.org/post")
|
||||
/// .body(bytes)
|
||||
/// .send()?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn body<T: Into<Body>>(&mut self, body: T) -> &mut RequestBuilder {
|
||||
*self.request_mut().body_mut() = Some(body.into());
|
||||
if let Some(req) = request_mut(&mut self.request, &self.err) {
|
||||
*req.body_mut() = Some(body.into());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -217,9 +224,9 @@ impl RequestBuilder {
|
||||
/// let mut params = HashMap::new();
|
||||
/// params.insert("lang", "rust");
|
||||
///
|
||||
/// let client = reqwest::Client::new()?;
|
||||
/// let res = client.post("http://httpbin.org")?
|
||||
/// .form(¶ms)?
|
||||
/// let client = reqwest::Client::new();
|
||||
/// let res = client.post("http://httpbin.org")
|
||||
/// .form(¶ms)
|
||||
/// .send()?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
@@ -229,16 +236,17 @@ impl RequestBuilder {
|
||||
///
|
||||
/// This method fails if the passed value cannot be serialized into
|
||||
/// url encoded format
|
||||
pub fn form<T: Serialize>(&mut self, form: &T) -> ::Result<&mut RequestBuilder> {
|
||||
|
||||
{
|
||||
// check request_mut() before running serde
|
||||
let req = self.request_mut();
|
||||
let body = try_!(serde_urlencoded::to_string(form));
|
||||
req.headers_mut().set(ContentType::form_url_encoded());
|
||||
*req.body_mut() = Some(body.into());
|
||||
pub fn form<T: Serialize>(&mut self, form: &T) -> &mut RequestBuilder {
|
||||
if let Some(req) = request_mut(&mut self.request, &self.err) {
|
||||
match serde_urlencoded::to_string(form) {
|
||||
Ok(body) => {
|
||||
req.headers_mut().set(ContentType::form_url_encoded());
|
||||
*req.body_mut() = Some(body.into());
|
||||
},
|
||||
Err(err) => self.err = Some(::error::from(err)),
|
||||
}
|
||||
}
|
||||
Ok(self)
|
||||
self
|
||||
}
|
||||
|
||||
/// Send a JSON body.
|
||||
@@ -254,9 +262,9 @@ impl RequestBuilder {
|
||||
/// let mut map = HashMap::new();
|
||||
/// map.insert("lang", "rust");
|
||||
///
|
||||
/// let client = reqwest::Client::new()?;
|
||||
/// let res = client.post("http://httpbin.org")?
|
||||
/// .json(&map)?
|
||||
/// let client = reqwest::Client::new();
|
||||
/// let res = client.post("http://httpbin.org")
|
||||
/// .json(&map)
|
||||
/// .send()?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
@@ -266,15 +274,17 @@ impl RequestBuilder {
|
||||
///
|
||||
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
|
||||
/// fail, or if `T` contains a map with non-string keys.
|
||||
pub fn json<T: Serialize>(&mut self, json: &T) -> ::Result<&mut RequestBuilder> {
|
||||
{
|
||||
// check request_mut() before running serde
|
||||
let req = self.request_mut();
|
||||
let body = try_!(serde_json::to_vec(json));
|
||||
req.headers_mut().set(ContentType::json());
|
||||
*req.body_mut() = Some(body.into());
|
||||
pub fn json<T: Serialize>(&mut self, json: &T) -> &mut RequestBuilder {
|
||||
if let Some(req) = request_mut(&mut self.request, &self.err) {
|
||||
match serde_json::to_vec(json) {
|
||||
Ok(body) => {
|
||||
req.headers_mut().set(ContentType::json());
|
||||
*req.body_mut() = Some(body.into());
|
||||
},
|
||||
Err(err) => self.err = Some(::error::from(err)),
|
||||
}
|
||||
}
|
||||
Ok(self)
|
||||
self
|
||||
}
|
||||
|
||||
/// Sends a multipart/form-data body.
|
||||
@@ -284,12 +294,12 @@ impl RequestBuilder {
|
||||
/// # use reqwest::Error;
|
||||
///
|
||||
/// # fn run() -> Result<(), Box<std::error::Error>> {
|
||||
/// let client = reqwest::Client::new()?;
|
||||
/// let client = reqwest::Client::new();
|
||||
/// let form = reqwest::multipart::Form::new()
|
||||
/// .text("key3", "value3")
|
||||
/// .file("file", "/path/to/field")?;
|
||||
///
|
||||
/// let response = client.post("your url")?
|
||||
/// let response = client.post("your url")
|
||||
/// .multipart(form)
|
||||
/// .send()?;
|
||||
/// # Ok(())
|
||||
@@ -298,8 +308,7 @@ impl RequestBuilder {
|
||||
///
|
||||
/// See [`multipart`](multipart/) for more examples.
|
||||
pub fn multipart(&mut self, mut multipart: ::multipart::Form) -> &mut RequestBuilder {
|
||||
{
|
||||
let req = self.request_mut();
|
||||
if let Some(req) = request_mut(&mut self.request, &self.err) {
|
||||
req.headers_mut().set(
|
||||
::header::ContentType(format!("multipart/form-data; boundary={}", ::multipart_::boundary(&multipart))
|
||||
.parse().unwrap()
|
||||
@@ -320,10 +329,14 @@ impl RequestBuilder {
|
||||
///
|
||||
/// This method consumes builder internal state. It panics on an attempt to
|
||||
/// reuse already consumed builder.
|
||||
pub fn build(&mut self) -> Request {
|
||||
self.request
|
||||
.take()
|
||||
.expect("RequestBuilder cannot be reused after builder a Request")
|
||||
pub fn build(&mut self) -> ::Result<Request> {
|
||||
if let Some(err) = self.err.take() {
|
||||
Err(err)
|
||||
} else {
|
||||
Ok(self.request
|
||||
.take()
|
||||
.expect("RequestBuilder cannot be reused after builder a Request"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs the Request and sends it the target URL, returning a Response.
|
||||
@@ -333,16 +346,18 @@ impl RequestBuilder {
|
||||
/// This method fails if there was an error while sending request,
|
||||
/// redirect loop was detected or redirect limit was exhausted.
|
||||
pub fn send(&mut self) -> ::Result<::Response> {
|
||||
let request = self.build();
|
||||
let request = self.build()?;
|
||||
self.client.execute(request)
|
||||
}
|
||||
|
||||
// private
|
||||
}
|
||||
|
||||
fn request_mut(&mut self) -> &mut Request {
|
||||
self.request
|
||||
.as_mut()
|
||||
.expect("RequestBuilder cannot be reused after builder a Request")
|
||||
|
||||
fn request_mut<'a>(req: &'a mut Option<Request>, err: &Option<::Error>) -> Option<&'a mut Request> {
|
||||
if err.is_some() {
|
||||
None
|
||||
} else {
|
||||
req.as_mut()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -375,10 +390,18 @@ fn fmt_request_fields<'a, 'b>(f: &'a mut fmt::DebugStruct<'a, 'b>, req: &Request
|
||||
// pub(crate)
|
||||
|
||||
#[inline]
|
||||
pub fn builder(client: Client, req: Request) -> RequestBuilder {
|
||||
RequestBuilder {
|
||||
client: client,
|
||||
request: Some(req),
|
||||
pub fn builder(client: Client, req: ::Result<Request>) -> RequestBuilder {
|
||||
match req {
|
||||
Ok(req) => RequestBuilder {
|
||||
client: client,
|
||||
request: Some(req),
|
||||
err: None,
|
||||
},
|
||||
Err(err) => RequestBuilder {
|
||||
client: client,
|
||||
request: None,
|
||||
err: Some(err)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,9 +431,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn basic_get_request() {
|
||||
let client = Client::new().unwrap();
|
||||
let client = Client::new();
|
||||
let some_url = "https://google.com/";
|
||||
let r = client.get(some_url).unwrap().build();
|
||||
let r = client.get(some_url).build().unwrap();
|
||||
|
||||
assert_eq!(r.method(), &Method::Get);
|
||||
assert_eq!(r.url().as_str(), some_url);
|
||||
@@ -418,9 +441,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn basic_head_request() {
|
||||
let client = Client::new().unwrap();
|
||||
let client = Client::new();
|
||||
let some_url = "https://google.com/";
|
||||
let r = client.head(some_url).unwrap().build();
|
||||
let r = client.head(some_url).build().unwrap();
|
||||
|
||||
assert_eq!(r.method(), &Method::Head);
|
||||
assert_eq!(r.url().as_str(), some_url);
|
||||
@@ -428,9 +451,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn basic_post_request() {
|
||||
let client = Client::new().unwrap();
|
||||
let client = Client::new();
|
||||
let some_url = "https://google.com/";
|
||||
let r = client.post(some_url).unwrap().build();
|
||||
let r = client.post(some_url).build().unwrap();
|
||||
|
||||
assert_eq!(r.method(), &Method::Post);
|
||||
assert_eq!(r.url().as_str(), some_url);
|
||||
@@ -438,9 +461,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn basic_put_request() {
|
||||
let client = Client::new().unwrap();
|
||||
let client = Client::new();
|
||||
let some_url = "https://google.com/";
|
||||
let r = client.put(some_url).unwrap().build();
|
||||
let r = client.put(some_url).build().unwrap();
|
||||
|
||||
assert_eq!(r.method(), &Method::Put);
|
||||
assert_eq!(r.url().as_str(), some_url);
|
||||
@@ -448,9 +471,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn basic_patch_request() {
|
||||
let client = Client::new().unwrap();
|
||||
let client = Client::new();
|
||||
let some_url = "https://google.com/";
|
||||
let r = client.patch(some_url).unwrap().build();
|
||||
let r = client.patch(some_url).build().unwrap();
|
||||
|
||||
assert_eq!(r.method(), &Method::Patch);
|
||||
assert_eq!(r.url().as_str(), some_url);
|
||||
@@ -458,9 +481,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn basic_delete_request() {
|
||||
let client = Client::new().unwrap();
|
||||
let client = Client::new();
|
||||
let some_url = "https://google.com/";
|
||||
let r = client.delete(some_url).unwrap().build();
|
||||
let r = client.delete(some_url).build().unwrap();
|
||||
|
||||
assert_eq!(r.method(), &Method::Delete);
|
||||
assert_eq!(r.url().as_str(), some_url);
|
||||
@@ -468,14 +491,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn add_header() {
|
||||
let client = Client::new().unwrap();
|
||||
let client = Client::new();
|
||||
let some_url = "https://google.com/";
|
||||
let mut r = client.post(some_url).unwrap();
|
||||
let mut r = client.post(some_url);
|
||||
|
||||
let header = Host::new("google.com", None);
|
||||
|
||||
// Add a copy of the header to the request builder
|
||||
let r = r.header(header.clone()).build();
|
||||
let r = r.header(header.clone()).build().unwrap();
|
||||
|
||||
// then check it was actually added
|
||||
assert_eq!(r.headers().get::<Host>(), Some(&header));
|
||||
@@ -483,9 +506,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn add_headers() {
|
||||
let client = Client::new().unwrap();
|
||||
let client = Client::new();
|
||||
let some_url = "https://google.com/";
|
||||
let mut r = client.post(some_url).unwrap();
|
||||
let mut r = client.post(some_url);
|
||||
|
||||
let header = Host::new("google.com", None);
|
||||
|
||||
@@ -493,7 +516,7 @@ mod tests {
|
||||
headers.set(header);
|
||||
|
||||
// Add a copy of the headers to the request builder
|
||||
let r = r.headers(headers.clone()).build();
|
||||
let r = r.headers(headers.clone()).build().unwrap();
|
||||
|
||||
// then make sure they were added correctly
|
||||
assert_eq!(r.headers(), &headers);
|
||||
@@ -501,13 +524,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn add_body() {
|
||||
let client = Client::new().unwrap();
|
||||
let client = Client::new();
|
||||
let some_url = "https://google.com/";
|
||||
let mut r = client.post(some_url).unwrap();
|
||||
let mut r = client.post(some_url);
|
||||
|
||||
let body = "Some interesting content";
|
||||
|
||||
let mut r = r.body(body).build();
|
||||
let mut r = r.body(body).build().unwrap();
|
||||
|
||||
let buf = body::read_to_string(r.body_mut().take().unwrap()).unwrap();
|
||||
|
||||
@@ -516,14 +539,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn add_form() {
|
||||
let client = Client::new().unwrap();
|
||||
let client = Client::new();
|
||||
let some_url = "https://google.com/";
|
||||
let mut r = client.post(some_url).unwrap();
|
||||
let mut r = client.post(some_url);
|
||||
|
||||
let mut form_data = HashMap::new();
|
||||
form_data.insert("foo", "bar");
|
||||
|
||||
let mut r = r.form(&form_data).unwrap().build();
|
||||
let mut r = r.form(&form_data).build().unwrap();
|
||||
|
||||
// Make sure the content type was set
|
||||
assert_eq!(r.headers().get::<ContentType>(),
|
||||
@@ -537,14 +560,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn add_json() {
|
||||
let client = Client::new().unwrap();
|
||||
let client = Client::new();
|
||||
let some_url = "https://google.com/";
|
||||
let mut r = client.post(some_url).unwrap();
|
||||
let mut r = client.post(some_url);
|
||||
|
||||
let mut json_data = HashMap::new();
|
||||
json_data.insert("foo", "bar");
|
||||
|
||||
let mut r = r.json(&json_data).unwrap().build();
|
||||
let mut r = r.json(&json_data).build().unwrap();
|
||||
|
||||
// Make sure the content type was set
|
||||
assert_eq!(r.headers().get::<ContentType>(), Some(&ContentType::json()));
|
||||
@@ -568,10 +591,10 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
let client = Client::new().unwrap();
|
||||
let client = Client::new();
|
||||
let some_url = "https://google.com/";
|
||||
let mut r = client.post(some_url).unwrap();
|
||||
let mut r = client.post(some_url);
|
||||
let json_data = MyStruct;
|
||||
assert!(r.json(&json_data).unwrap_err().is_serialization());
|
||||
assert!(r.json(&json_data).build().unwrap_err().is_serialization());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,8 +63,8 @@ impl Response {
|
||||
/// use reqwest::Client;
|
||||
/// use reqwest::StatusCode;
|
||||
/// # fn run() -> Result<(), Box<::std::error::Error>> {
|
||||
/// let client = Client::new()?;
|
||||
/// let resp = client.post("http://httpbin.org/post")?
|
||||
/// let client = Client::new();
|
||||
/// let resp = client.post("http://httpbin.org/post")
|
||||
/// .body("possibly too large")
|
||||
/// .send()?;
|
||||
/// match resp.status() {
|
||||
@@ -94,8 +94,8 @@ impl Response {
|
||||
/// # use reqwest::header::ContentLength;
|
||||
/// #
|
||||
/// # fn run() -> Result<(), Box<::std::error::Error>> {
|
||||
/// let client = Client::new()?;
|
||||
/// let mut resp = client.head("http://httpbin.org/bytes/3000")?.send()?;
|
||||
/// let client = Client::new();
|
||||
/// let mut resp = client.head("http://httpbin.org/bytes/3000").send()?;
|
||||
/// if resp.status().is_success() {
|
||||
/// let len = resp.headers().get::<ContentLength>()
|
||||
/// .map(|ct_len| **ct_len)
|
||||
|
||||
@@ -61,10 +61,9 @@ fn test_gzip(response_size: usize, chunk_size: usize) {
|
||||
|
||||
let mut core = Core::new().unwrap();
|
||||
|
||||
let client = Client::new(&core.handle()).unwrap();
|
||||
let client = Client::new(&core.handle());
|
||||
|
||||
let res_future = client.get(&format!("http://{}/gzip", server.addr()))
|
||||
.unwrap()
|
||||
.send()
|
||||
.and_then(|mut res| {
|
||||
let body = mem::replace(res.body_mut(), Decoder::empty());
|
||||
|
||||
@@ -62,9 +62,7 @@ fn test_post() {
|
||||
|
||||
let url = format!("http://{}/2", server.addr());
|
||||
let mut res = reqwest::Client::new()
|
||||
.unwrap()
|
||||
.post(&url)
|
||||
.unwrap()
|
||||
.body("Hello")
|
||||
.send()
|
||||
.unwrap();
|
||||
|
||||
@@ -68,10 +68,9 @@ fn test_gzip_empty_body() {
|
||||
\r\n"
|
||||
};
|
||||
|
||||
let client = reqwest::Client::new().unwrap();
|
||||
let client = reqwest::Client::new();
|
||||
let mut res = client
|
||||
.head(&format!("http://{}/gzip", server.addr()))
|
||||
.unwrap()
|
||||
.send()
|
||||
.unwrap();
|
||||
|
||||
@@ -127,11 +126,10 @@ fn test_accept_header_is_not_changed_if_set() {
|
||||
\r\n\
|
||||
"
|
||||
};
|
||||
let client = reqwest::Client::new().unwrap();
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
let res = client
|
||||
.get(&format!("http://{}/accept", server.addr()))
|
||||
.unwrap()
|
||||
.header(reqwest::header::Accept::json())
|
||||
.send()
|
||||
.unwrap();
|
||||
@@ -157,10 +155,9 @@ fn test_accept_encoding_header_is_not_changed_if_set() {
|
||||
\r\n\
|
||||
"
|
||||
};
|
||||
let client = reqwest::Client::new().unwrap();
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
let res = client.get(&format!("http://{}/accept-encoding", server.addr()))
|
||||
.unwrap()
|
||||
.header(reqwest::header::AcceptEncoding(
|
||||
vec![reqwest::header::qitem(reqwest::header::Encoding::Identity)]
|
||||
))
|
||||
|
||||
@@ -38,9 +38,7 @@ fn test_multipart() {
|
||||
let url = format!("http://{}/multipart/1", server.addr());
|
||||
|
||||
let res = reqwest::Client::new()
|
||||
.unwrap()
|
||||
.post(&url)
|
||||
.unwrap()
|
||||
.multipart(form)
|
||||
.send()
|
||||
.unwrap();
|
||||
|
||||
@@ -26,12 +26,10 @@ fn test_http_proxy() {
|
||||
|
||||
let url = "http://hyper.rs/prox";
|
||||
let res = reqwest::Client::builder()
|
||||
.unwrap()
|
||||
.proxy(reqwest::Proxy::http(&proxy).unwrap())
|
||||
.build()
|
||||
.unwrap()
|
||||
.get(url)
|
||||
.unwrap()
|
||||
.send()
|
||||
.unwrap();
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ mod support;
|
||||
|
||||
#[test]
|
||||
fn test_redirect_301_and_302_and_303_changes_post_to_get() {
|
||||
let client = reqwest::Client::new().unwrap();
|
||||
let client = reqwest::Client::new();
|
||||
let codes = [301, 302, 303];
|
||||
|
||||
for code in codes.iter() {
|
||||
@@ -47,7 +47,6 @@ fn test_redirect_301_and_302_and_303_changes_post_to_get() {
|
||||
let url = format!("http://{}/{}", redirect.addr(), code);
|
||||
let dst = format!("http://{}/{}", redirect.addr(), "dst");
|
||||
let res = client.post(&url)
|
||||
.unwrap()
|
||||
.send()
|
||||
.unwrap();
|
||||
assert_eq!(res.url().as_str(), dst);
|
||||
@@ -59,7 +58,7 @@ fn test_redirect_301_and_302_and_303_changes_post_to_get() {
|
||||
|
||||
#[test]
|
||||
fn test_redirect_307_and_308_tries_to_get_again() {
|
||||
let client = reqwest::Client::new().unwrap();
|
||||
let client = reqwest::Client::new();
|
||||
let codes = [307, 308];
|
||||
for code in codes.iter() {
|
||||
let redirect = server! {
|
||||
@@ -100,7 +99,6 @@ fn test_redirect_307_and_308_tries_to_get_again() {
|
||||
let url = format!("http://{}/{}", redirect.addr(), code);
|
||||
let dst = format!("http://{}/{}", redirect.addr(), "dst");
|
||||
let res = client.get(&url)
|
||||
.unwrap()
|
||||
.send()
|
||||
.unwrap();
|
||||
assert_eq!(res.url().as_str(), dst);
|
||||
@@ -112,7 +110,7 @@ fn test_redirect_307_and_308_tries_to_get_again() {
|
||||
|
||||
#[test]
|
||||
fn test_redirect_307_and_308_tries_to_post_again() {
|
||||
let client = reqwest::Client::new().unwrap();
|
||||
let client = reqwest::Client::new();
|
||||
let codes = [307, 308];
|
||||
for code in codes.iter() {
|
||||
let redirect = server! {
|
||||
@@ -157,7 +155,6 @@ fn test_redirect_307_and_308_tries_to_post_again() {
|
||||
let url = format!("http://{}/{}", redirect.addr(), code);
|
||||
let dst = format!("http://{}/{}", redirect.addr(), "dst");
|
||||
let res = client.post(&url)
|
||||
.unwrap()
|
||||
.body("Hello")
|
||||
.send()
|
||||
.unwrap();
|
||||
@@ -170,7 +167,7 @@ fn test_redirect_307_and_308_tries_to_post_again() {
|
||||
|
||||
#[test]
|
||||
fn test_redirect_307_does_not_try_if_reader_cannot_reset() {
|
||||
let client = reqwest::Client::new().unwrap();
|
||||
let client = reqwest::Client::new();
|
||||
let codes = [307, 308];
|
||||
for &code in codes.iter() {
|
||||
let redirect = server! {
|
||||
@@ -199,7 +196,6 @@ fn test_redirect_307_does_not_try_if_reader_cannot_reset() {
|
||||
let url = format!("http://{}/{}", redirect.addr(), code);
|
||||
let res = client
|
||||
.post(&url)
|
||||
.unwrap()
|
||||
.body(reqwest::Body::new(&b"Hello"[..]))
|
||||
.send()
|
||||
.unwrap();
|
||||
@@ -251,12 +247,10 @@ fn test_redirect_removes_sensitive_headers() {
|
||||
let mut cookie = reqwest::header::Cookie::new();
|
||||
cookie.set("foo", "bar");
|
||||
reqwest::Client::builder()
|
||||
.unwrap()
|
||||
.referer(false)
|
||||
.build()
|
||||
.unwrap()
|
||||
.get(&format!("http://{}/sensitive", mid_server.addr()))
|
||||
.unwrap()
|
||||
.header(cookie)
|
||||
.send()
|
||||
.unwrap();
|
||||
@@ -309,12 +303,10 @@ fn test_redirect_policy_can_stop_redirects_without_an_error() {
|
||||
let url = format!("http://{}/no-redirect", server.addr());
|
||||
|
||||
let res = reqwest::Client::builder()
|
||||
.unwrap()
|
||||
.redirect(reqwest::RedirectPolicy::none())
|
||||
.build()
|
||||
.unwrap()
|
||||
.get(&url)
|
||||
.unwrap()
|
||||
.send()
|
||||
.unwrap();
|
||||
|
||||
@@ -359,12 +351,12 @@ fn test_referer_is_not_set_if_disabled() {
|
||||
\r\n\
|
||||
"
|
||||
};
|
||||
reqwest::Client::builder().unwrap()
|
||||
reqwest::Client::builder()
|
||||
.referer(false)
|
||||
.build().unwrap()
|
||||
.build()
|
||||
.unwrap()
|
||||
//client
|
||||
.get(&format!("http://{}/no-refer", server.addr()))
|
||||
.unwrap()
|
||||
.send()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
@@ -30,12 +30,10 @@ fn test_write_timeout() {
|
||||
|
||||
let url = format!("http://{}/write-timeout", server.addr());
|
||||
let err = reqwest::Client::builder()
|
||||
.unwrap()
|
||||
.timeout(Duration::from_millis(500))
|
||||
.build()
|
||||
.unwrap()
|
||||
.post(&url)
|
||||
.unwrap()
|
||||
.header(reqwest::header::ContentLength(5))
|
||||
.body(reqwest::Body::new(&b"Hello"[..]))
|
||||
.send()
|
||||
@@ -66,12 +64,10 @@ fn test_response_timeout() {
|
||||
|
||||
let url = format!("http://{}/response-timeout", server.addr());
|
||||
let err = reqwest::Client::builder()
|
||||
.unwrap()
|
||||
.timeout(Duration::from_millis(500))
|
||||
.build()
|
||||
.unwrap()
|
||||
.get(&url)
|
||||
.unwrap()
|
||||
.send()
|
||||
.unwrap_err();
|
||||
|
||||
@@ -101,12 +97,10 @@ fn test_read_timeout() {
|
||||
|
||||
let url = format!("http://{}/read-timeout", server.addr());
|
||||
let mut res = reqwest::Client::builder()
|
||||
.unwrap()
|
||||
.timeout(Duration::from_millis(500))
|
||||
.build()
|
||||
.unwrap()
|
||||
.get(&url)
|
||||
.unwrap()
|
||||
.send()
|
||||
.unwrap();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user