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