ureq/lib.rs
1//!<div align="center">
2//! <!-- Version -->
3//! <a href="https://crates.io/crates/ureq">
4//! <img src="https://img.shields.io/crates/v/ureq.svg?style=flat-square"
5//! alt="Crates.io version" />
6//! </a>
7//! <!-- Docs -->
8//! <a href="https://docs.rs/ureq">
9//! <img src="https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square"
10//! alt="docs.rs docs" />
11//! </a>
12//! <!-- Downloads -->
13//! <a href="https://crates.io/crates/ureq">
14//! <img src="https://img.shields.io/crates/d/ureq.svg?style=flat-square"
15//! alt="Crates.io downloads" />
16//! </a>
17//!</div>
18//!
19//! A simple, safe HTTP client.
20//!
21//! Ureq's first priority is being easy for you to use. It's great for
22//! anyone who wants a low-overhead HTTP client that just gets the job done. Works
23//! very well with HTTP APIs. Its features include cookies, JSON, HTTP proxies,
24//! HTTPS, charset decoding, and is based on the API of the `http` crate.
25//!
26//! Ureq is in pure Rust for safety and ease of understanding. It avoids using
27//! `unsafe` directly. It uses blocking I/O instead of async I/O, because that keeps
28//! the API simple and keeps dependencies to a minimum. For TLS, ureq uses
29//! rustls or native-tls.
30//!
31//! See the [changelog] for details of recent releases.
32//!
33//! [changelog]: https://github.com/algesten/ureq/blob/main/CHANGELOG.md
34//!
35//! # Usage
36//!
37//! In its simplest form, ureq looks like this:
38//!
39//! ```rust
40//! let body: String = ureq::get("http://example.com")
41//! .header("Example-Header", "header value")
42//! .call()?
43//! .body_mut()
44//! .read_to_string()?;
45//! # Ok::<(), ureq::Error>(())
46//! ```
47//!
48//! For more involved tasks, you'll want to create an [`Agent`]. An Agent
49//! holds a connection pool for reuse, and a cookie store if you use the
50//! **cookies** feature. An Agent can be cheaply cloned due to internal
51//! [`Arc`] and all clones of an Agent share state among each other. Creating
52//! an Agent also allows setting options like the TLS configuration.
53//!
54//! ```rust
55//! # fn no_run() -> Result<(), ureq::Error> {
56//! use ureq::Agent;
57//! use std::time::Duration;
58//!
59//! let mut config = Agent::config_builder()
60//! .timeout_global(Some(Duration::from_secs(5)))
61//! .build();
62//!
63//! let agent: Agent = config.into();
64//!
65//! let body: String = agent.get("http://example.com/page")
66//! .call()?
67//! .body_mut()
68//! .read_to_string()?;
69//!
70//! // Reuses the connection from previous request.
71//! let response: String = agent.put("http://example.com/upload")
72//! .header("Authorization", "example-token")
73//! .send("some body data")?
74//! .body_mut()
75//! .read_to_string()?;
76//! # Ok(())}
77//! ```
78//!
79//! ## JSON
80//!
81//! Ureq supports sending and receiving json, if you enable the **json** feature:
82//!
83//! ```rust
84//! # #[cfg(feature = "json")]
85//! # fn no_run() -> Result<(), ureq::Error> {
86//! use serde::{Serialize, Deserialize};
87//!
88//! #[derive(Serialize)]
89//! struct MySendBody {
90//! thing: String,
91//! }
92//!
93//! #[derive(Deserialize)]
94//! struct MyRecvBody {
95//! other: String,
96//! }
97//!
98//! let send_body = MySendBody { thing: "yo".to_string() };
99//!
100//! // Requires the `json` feature enabled.
101//! let recv_body = ureq::post("http://example.com/post/ingest")
102//! .header("X-My-Header", "Secret")
103//! .send_json(&send_body)?
104//! .body_mut()
105//! .read_json::<MyRecvBody>()?;
106//! # Ok(())}
107//! ```
108//!
109//! ## Error handling
110//!
111//! ureq returns errors via `Result<T, ureq::Error>`. That includes I/O errors,
112//! protocol errors. By default, also HTTP status code errors (when the
113//! server responded 4xx or 5xx) results in [`Error`].
114//!
115//! This behavior can be turned off via [`http_status_as_error()`]
116//!
117//! ```rust
118//! use ureq::Error;
119//!
120//! # fn no_run() -> Result<(), ureq::Error> {
121//! match ureq::get("http://mypage.example.com/").call() {
122//! Ok(response) => { /* it worked */},
123//! Err(Error::StatusCode(code)) => {
124//! /* the server returned an unexpected status
125//! code (such as 400, 500 etc) */
126//! }
127//! Err(_) => { /* some kind of io/transport/etc error */ }
128//! }
129//! # Ok(())}
130//! ```
131//!
132//! # Features
133//!
134//! To enable a minimal dependency tree, some features are off by default.
135//! You can control them when including ureq as a dependency.
136//!
137//! `ureq = { version = "3", features = ["socks-proxy", "charset"] }`
138//!
139//! The default enabled features are: **rustls** and **gzip**.
140//!
141//! * **rustls** enables the rustls TLS implementation. This is the default for the the crate level
142//! convenience calls (`ureq::get` etc). It currently uses `ring` as the TLS provider.
143//! * **native-tls** enables the native tls backend for TLS. Due to the risk of diamond dependencies
144//! accidentally switching on an unwanted TLS implementation, `native-tls` is never picked up as
145//! a default or used by the crate level convenience calls (`ureq::get` etc) – it must be configured
146//! on the agent
147//! * **platform-verifier** enables verifying the server certificates using a method native to the
148//! platform ureq is executing on. See [rustls-platform-verifier] crate
149//! * **socks-proxy** enables proxy config using the `socks4://`, `socks4a://`, `socks5://`
150//! and `socks://` (equal to `socks5://`) prefix
151//! * **cookies** enables cookies
152//! * **gzip** enables requests of gzip-compressed responses and decompresses them
153//! * **brotli** enables requests brotli-compressed responses and decompresses them
154//! * **charset** enables interpreting the charset part of the Content-Type header
155//! (e.g. `Content-Type: text/plain; charset=iso-8859-1`). Without this, the
156//! library defaults to Rust's built in `utf-8`
157//! * **json** enables JSON sending and receiving via serde_json
158//!
159//! ### Unstable
160//!
161//! These features are unstable and might change in a minor version.
162//!
163//! * **rustls-no-provider** Enables rustls, but does not enable any [`CryptoProvider`] such as `ring`.
164//! Providers other than the default (currently `ring`) are never picked up from feature flags alone.
165//! It must be configured on the agent.
166//!
167//! * **vendored** compiles and statically links to a copy of non-Rust vendors (e.g. OpenSSL from `native-tls`)
168//!
169//! # TLS (https)
170//!
171//! ## rustls
172//!
173//! By default, ureq uses [`rustls` crate] with the `ring` cryptographic provider.
174//! As of Sep 2024, the `ring` provider has a higher chance of compiling successfully. If the user
175//! installs another process [default provider], that choice is respected.
176//!
177//! ureq does not guarantee to default to ring indefinitely. `rustls` as a feature flag will always
178//! work, but the specific crypto backend might change in a minor version.
179//!
180//! ```
181//! # #[cfg(feature = "rustls")]
182//! # {
183//! // This uses rustls
184//! ureq::get("https://www.google.com/").call().unwrap();
185//! # } Ok::<_, ureq::Error>(())
186//! ```
187//!
188//! ### rustls without ring
189//!
190//! ureq never changes TLS backend from feature flags alone. It is possible to compile ureq
191//! without ring, but it requires specific feature flags and configuring the [`Agent`].
192//!
193//! Since rustls is not semver 1.x, this requires non-semver-guaranteed API. I.e. ureq might
194//! change this behavior without a major version bump.
195//!
196//! Read more at [`TlsConfigBuilder::unversioned_rustls_crypto_provider`][crate::tls::TlsConfigBuilder::unversioned_rustls_crypto_provider].
197//!
198//! ## native-tls
199//!
200//! As an alternative, ureq ships with [`native-tls`] as a TLS provider. This must be
201//! enabled using the **native-tls** feature. Due to the risk of diamond dependencies
202//! accidentally switching on an unwanted TLS implementation, `native-tls` is never picked
203//! up as a default or used by the crate level convenience calls (`ureq::get` etc) – it
204//! must be configured on the agent.
205//!
206//! ```
207//! # #[cfg(feature = "native-tls")]
208//! # {
209//! use ureq::config::Config;
210//! use ureq::tls::{TlsConfig, TlsProvider};
211//!
212//! let mut config = Config::builder()
213//! .tls_config(
214//! TlsConfig::builder()
215//! // requires the native-tls feature
216//! .provider(TlsProvider::NativeTls)
217//! .build()
218//! )
219//! .build();
220//!
221//! let agent = config.new_agent();
222//!
223//! agent.get("https://www.google.com/").call().unwrap();
224//! # } Ok::<_, ureq::Error>(())
225//! ```
226//!
227//! ## Root certificates
228//!
229//! ### webpki-roots
230//!
231//! By default, ureq uses Mozilla's root certificates via the [webpki-roots] crate. This is a static
232//! bundle of root certificates that do not update automatically. It also circumvents whatever root
233//! certificates are installed on the host running ureq, which might be a good or a bad thing depending
234//! on your perspective. There is also no mechanism for [SCT], [CRL]s or other revocations.
235//! To maintain a "fresh" list of root certs, you need to bump the ureq dependency from time to time.
236//!
237//! The main reason for chosing this as the default is to minimize the number of dependencies. More
238//! details about this decision can be found at [PR 818].
239//!
240//! If your use case for ureq is talking to a limited number of servers with high trust, the
241//! default setting is likely sufficient. If you use ureq with a high number of servers, or servers
242//! you don't trust, we recommend using the platform verifier (see below).
243//!
244//! ### platform-verifier
245//!
246//! The [rustls-platform-verifier] crate provides access to natively checking the certificate via your OS.
247//! To use this verifier, you need to enable it using feature flag **platform-verifier** as well as
248//! configure an agent to use it.
249//!
250//! ```
251//! # #[cfg(all(feature = "rustls", feature="platform-verifier"))]
252//! # {
253//! use ureq::Agent;
254//! use ureq::tls::{TlsConfig, RootCerts};
255//!
256//! let agent = Agent::config_builder()
257//! .tls_config(
258//! TlsConfig::builder()
259//! .root_certs(RootCerts::PlatformVerifier)
260//! .build()
261//! )
262//! .build()
263//! .new_agent();
264//!
265//! let response = agent.get("https://httpbin.org/get").call()?;
266//! # } Ok::<_, ureq::Error>(())
267//! ```
268//!
269//! Setting `RootCerts::PlatformVerifier` together with `TlsProvider::NativeTls` means
270//! also native-tls will use the OS roots instead of [webpki-roots] crate. Whether that
271//! results in a config that has CRLs and revocations is up to whatever native-tls links to.
272//!
273//! # JSON
274//!
275//! By enabling the **json** feature, the library supports serde json.
276//!
277//! This is enabled by default.
278//!
279//! * [`request.send_json()`] send body as json.
280//! * [`body.read_json()`] transform response to json.
281//!
282//! # Sending body data
283//!
284//! HTTP/1.1 has two ways of transfering body data. Either of a known size with
285//! the `Content-Length` HTTP header, or unknown size with the
286//! `Transfer-Encoding: chunked` header. ureq supports both and will use the
287//! appropriate method depending on which body is being sent.
288//!
289//! ureq has a [`AsSendBody`] trait that is implemented for many well known types
290//! of data that we might want to send. The request body can thus be anything
291//! from a `String` to a `File`, see below.
292//!
293//! ## Content-Length
294//!
295//! The library will send a `Content-Length` header on requests with bodies of
296//! known size, in other words, if the body to send is one of:
297//!
298//! * `&[u8]`
299//! * `&[u8; N]`
300//! * `&str`
301//! * `String`
302//! * `&String`
303//! * `Vec<u8>`
304//! * `&Vec<u8>)`
305//! * [`SendBody::from_json()`] (implicitly via [`request.send_json()`])
306//!
307//! ## Transfer-Encoding: chunked
308//!
309//! ureq will send a `Transfer-Encoding: chunked` header on requests where the body
310//! is of unknown size. The body is automatically converted to an [`std::io::Read`]
311//! when the type is one of:
312//!
313//! * `File`
314//! * `&File`
315//! * `TcpStream`
316//! * `&TcpStream`
317//! * `Stdin`
318//! * `UnixStream` (not on windows)
319//!
320//! ### From readers
321//!
322//! The chunked method also applies for bodies constructed via:
323//!
324//! * [`SendBody::from_reader()`]
325//! * [`SendBody::from_owned_reader()`]
326//!
327//! ## Proxying a response body
328//!
329//! As a special case, when ureq sends a [`Body`] from a previous http call, the
330//! use of `Content-Length` or `chunked` depends on situation. For input such as
331//! gzip decoding (**gzip** feature) or charset transformation (**charset** feature),
332//! the output body might not match the input, which means ureq is forced to use
333//! the `chunked` method.
334//!
335//! * `Response<Body>`
336//!
337//! ## Sending form data
338//!
339//! [`request.send_form()`] provides a way to send `application/x-www-form-urlencoded`
340//! encoded data. The key/values provided will be URL encoded.
341//!
342//! ## Overriding
343//!
344//! If you set your own Content-Length or Transfer-Encoding header before
345//! sending the body, ureq will respect that header by not overriding it,
346//! and by encoding the body or not, as indicated by the headers you set.
347//!
348//! ```
349//! let resp = ureq::put("https://httpbin.org/put")
350//! .header("Transfer-Encoding", "chunked")
351//! .send("Hello world")?;
352//! # Ok::<_, ureq::Error>(())
353//! ```
354//!
355//! # Character encoding
356//!
357//! By enabling the **charset** feature, the library supports receiving other
358//! character sets than `utf-8`.
359//!
360//! For [`Body::read_to_string()`] we read the header like:
361//!
362//! `Content-Type: text/plain; charset=iso-8859-1`
363//!
364//! and if it contains a charset specification, we try to decode the body using that
365//! encoding. In the absence of, or failing to interpret the charset, we fall back on `utf-8`.
366//!
367//! Currently ureq does not provide a way to encode when sending request bodies.
368//!
369//! ## Lossy utf-8
370//!
371//! When reading text bodies (with a `Content-Type` starting `text/` as in `text/plain`,
372//! `text/html`, etc), ureq can ensure the body is possible to read as a `String` also if
373//! it contains characters that are not valid for utf-8. Invalid characters are replaced
374//! with a question mark `?` (NOT the utf-8 replacement character).
375//!
376//! For [`Body::read_to_string()`] this is turned on by default, but it can be disabled
377//! and conversely for [`Body::as_reader()`] it is not enabled, but can be.
378//!
379//! To precisely configure the behavior use [`Body::with_config()`].
380//!
381//! # Proxying
382//!
383//! ureq supports two kinds of proxies, [`HTTP`] ([`CONNECT`]), [`SOCKS4`]/[`SOCKS5`],
384//! the former is always available while the latter must be enabled using the feature
385//! **socks-proxy**.
386//!
387//! Proxies settings are configured on an [`Agent`]. All request sent through the agent will be proxied.
388//!
389//! ## Example using HTTP
390//!
391//! ```rust
392//! use ureq::{Agent, Proxy};
393//! # fn no_run() -> std::result::Result<(), ureq::Error> {
394//! // Configure an http connect proxy.
395//! let proxy = Proxy::new("http://user:password@cool.proxy:9090")?;
396//! let agent: Agent = Agent::config_builder()
397//! .proxy(Some(proxy))
398//! .build()
399//! .into();
400//!
401//! // This is proxied.
402//! let resp = agent.get("http://cool.server").call()?;
403//! # Ok(())}
404//! # fn main() {}
405//! ```
406//!
407//! ## Example using SOCKS5
408//!
409//! ```rust
410//! use ureq::{Agent, Proxy};
411//! # #[cfg(feature = "socks-proxy")]
412//! # fn no_run() -> std::result::Result<(), ureq::Error> {
413//! // Configure a SOCKS proxy.
414//! let proxy = Proxy::new("socks5://user:password@cool.proxy:9090")?;
415//! let agent: Agent = Agent::config_builder()
416//! .proxy(Some(proxy))
417//! .build()
418//! .into();
419//!
420//! // This is proxied.
421//! let resp = agent.get("http://cool.server").call()?;
422//! # Ok(())}
423//! ```
424//!
425//! # Log levels
426//!
427//! ureq uses the log crate. These are the definitions of the log levels, however we
428//! do not guarantee anything for dependencies such as `http` and `rustls`.
429//!
430//! * `ERROR` - nothing
431//! * `WARN` - if we detect a user configuration problem.
432//! * `INFO` - nothing
433//! * `DEBUG` - uri, state changes, transport, resolver and selected request/response headers
434//! * `TRACE` - wire level debug. NOT REDACTED!
435//!
436//! The request/response headers on DEBUG levels are allow-listed to only include headers that
437//! are considered safe. The code has the [allow list](https://github.com/algesten/ureq/blob/81127cfc38516903330dc1b9c618122372f8dc29/src/util.rs#L184-L198).
438//!
439//! # Versioning
440//!
441//! ## Semver and `unversioned`
442//!
443//! ureq follows semver. From ureq 3.x we strive to have a much closer adherence to semver than 2.x.
444//! The main mistake in 2.x was to re-export crates that were not yet semver 1.0. In ureq 3.x TLS and
445//! cookie configuration is shimmed using our own types.
446//!
447//! ureq 3.x is trying out two new traits that had no equivalent in 2.x, [`Transport`] and [`Resolver`].
448//! These allow the user write their own bespoke transports and (DNS name) resolver. The API:s for
449//! these parts are not yet solidified. They live under the [`unversioned`] module, and do not
450//! follow semver. See module doc for more info.
451//!
452//! ## Breaking changes in dependencies
453//!
454//! ureq relies on non-semver 1.x crates such as `rustls` and `native-tls`. Some scenarios, such
455//! as configuring `rustls` to not use `ring`, a user of ureq might need to interact with these
456//! crates directly instead of going via ureq's provided API.
457//!
458//! Such changes can break when ureq updates dependencies. This is not considered a breaking change
459//! for ureq and will not be reflected by a major version bump.
460//!
461//! We strive to mark ureq's API with the word "unversioned" to identify places where this risk arises.
462//!
463//! ## Minimum Supported Rust Version (MSRV)
464//!
465//! From time to time we will need to update our minimum supported Rust version (MSRV). This is not
466//! something we do lightly; our ambition is to be as conservative with MSRV as possible.
467//!
468//! * For some dependencies, we will opt for pinning the version of the dep instead
469//! of bumping our MSRV.
470//! * For important dependencies, like the TLS libraries, we cannot hold back our MSRV if they change.
471//! * We do not consider MSRV changes to be breaking for the purposes of semver.
472//! * We will not make MSRV changes in patch releases.
473//! * MSRV changes will get their own minor release, and not be co-mingled with other changes.
474//!
475//! [`HTTP`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Proxy_servers_and_tunneling#http_tunneling
476//! [`CONNECT`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT
477//! [`SOCKS4`]: https://en.wikipedia.org/wiki/SOCKS#SOCKS4
478//! [`SOCKS5`]: https://en.wikipedia.org/wiki/SOCKS#SOCKS5
479//! [`rustls` crate]: https://crates.io/crates/rustls
480//! [default provider]: https://docs.rs/rustls/latest/rustls/crypto/struct.CryptoProvider.html#method.install_default
481//! [`native-tls`]: https://crates.io/crates/native-tls
482//! [rustls-platform-verifier]: https://crates.io/crates/rustls-platform-verifier
483//! [webpki-roots]: https://crates.io/crates/webpki-roots
484//! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
485//! [`Agent`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.Agent.html
486//! [`Error`]: https://docs.rs/ureq/3.0.0-rc4/ureq/enum.Error.html
487//! [`http_status_as_error()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/config/struct.ConfigBuilder.html#method.http_status_as_error
488//! [SCT]: https://en.wikipedia.org/wiki/Certificate_Transparency
489//! [CRL]: https://en.wikipedia.org/wiki/Certificate_revocation_list
490//! [PR818]: https://github.com/algesten/ureq/pull/818
491//! [`request.send_json()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.RequestBuilder.html#method.send_json
492//! [`body.read_json()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.Body.html#method.read_json
493//! [`AsSendBody`]: https://docs.rs/ureq/3.0.0-rc4/ureq/trait.AsSendBody.html
494//! [`SendBody::from_json()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.SendBody.html#method.from_json
495//! [`std::io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
496//! [`SendBody::from_reader()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.SendBody.html#method.from_reader
497//! [`SendBody::from_owned_reader()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.SendBody.html#method.from_owned_reader
498//! [`Body`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.Body.html
499//! [`request.send_form()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.RequestBuilder.html#method.send_form
500//! [`Body::read_to_string()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.Body.html#method.read_to_string
501//! [`Body::as_reader()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.Body.html#method.as_reader
502//! [`Body::with_config()`]: https://docs.rs/ureq/3.0.0-rc4/ureq/struct.Body.html#method.with_config
503//! [`Transport`]: https://docs.rs/ureq/3.0.0-rc4/ureq/unversioned/transport/trait.Transport.html
504//! [`Resolver`]: https://docs.rs/ureq/3.0.0-rc4/ureq/unversioned/resolver/trait.Resolver.html
505//! [`unversioned`]: https://docs.rs/ureq/3.0.0-rc4/ureq/unversioned/index.html
506//! [`CryptoProvider`]: https://docs.rs/rustls/latest/rustls/crypto/struct.CryptoProvider.html
507
508#![forbid(unsafe_code)]
509#![warn(clippy::all)]
510#![deny(missing_docs)]
511// I don't think elided lifetimes help in understanding the code.
512#![allow(clippy::needless_lifetimes)]
513
514#[macro_use]
515extern crate log;
516
517use std::convert::TryFrom;
518
519/// Re-exported http-crate.
520pub use ureq_proto::http;
521
522pub use body::{Body, BodyBuilder, BodyReader, BodyWithConfig};
523use http::Method;
524use http::{Request, Response, Uri};
525pub use proxy::Proxy;
526pub use request::RequestBuilder;
527use request::{WithBody, WithoutBody};
528pub use request_ext::RequestExt;
529pub use response::ResponseExt;
530pub use send_body::AsSendBody;
531
532mod agent;
533mod body;
534pub mod config;
535mod error;
536mod pool;
537mod proxy;
538mod query;
539mod request;
540mod response;
541mod run;
542mod send_body;
543mod timings;
544mod util;
545
546pub mod unversioned;
547use unversioned::resolver;
548use unversioned::transport;
549
550pub mod middleware;
551
552#[cfg(feature = "_tls")]
553pub mod tls;
554
555#[cfg(feature = "cookies")]
556mod cookies;
557mod request_ext;
558
559#[cfg(feature = "cookies")]
560pub use cookies::{Cookie, CookieJar};
561
562pub use agent::Agent;
563pub use error::Error;
564pub use send_body::SendBody;
565pub use timings::Timeout;
566
567/// Typestate variables.
568pub mod typestate {
569 pub use super::request::WithBody;
570 pub use super::request::WithoutBody;
571
572 pub use super::config::typestate::AgentScope;
573 pub use super::config::typestate::HttpCrateScope;
574 pub use super::config::typestate::RequestScope;
575}
576
577/// Run a [`http::Request<impl AsSendBody>`].
578pub fn run(request: Request<impl AsSendBody>) -> Result<Response<Body>, Error> {
579 let agent = Agent::new_with_defaults();
580 agent.run(request)
581}
582
583/// A new [Agent] with default configuration
584///
585/// Agents are used to hold configuration and keep state between requests.
586pub fn agent() -> Agent {
587 Agent::new_with_defaults()
588}
589
590/// Make a GET request.
591///
592/// Run on a use-once [`Agent`].
593#[must_use]
594pub fn get<T>(uri: T) -> RequestBuilder<WithoutBody>
595where
596 Uri: TryFrom<T>,
597 <Uri as TryFrom<T>>::Error: Into<http::Error>,
598{
599 RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::GET, uri)
600}
601
602/// Make a POST request.
603///
604/// Run on a use-once [`Agent`].
605#[must_use]
606pub fn post<T>(uri: T) -> RequestBuilder<WithBody>
607where
608 Uri: TryFrom<T>,
609 <Uri as TryFrom<T>>::Error: Into<http::Error>,
610{
611 RequestBuilder::<WithBody>::new(Agent::new_with_defaults(), Method::POST, uri)
612}
613
614/// Make a PUT request.
615///
616/// Run on a use-once [`Agent`].
617#[must_use]
618pub fn put<T>(uri: T) -> RequestBuilder<WithBody>
619where
620 Uri: TryFrom<T>,
621 <Uri as TryFrom<T>>::Error: Into<http::Error>,
622{
623 RequestBuilder::<WithBody>::new(Agent::new_with_defaults(), Method::PUT, uri)
624}
625
626/// Make a DELETE request.
627///
628/// Run on a use-once [`Agent`].
629#[must_use]
630pub fn delete<T>(uri: T) -> RequestBuilder<WithoutBody>
631where
632 Uri: TryFrom<T>,
633 <Uri as TryFrom<T>>::Error: Into<http::Error>,
634{
635 RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::DELETE, uri)
636}
637
638/// Make a HEAD request.
639///
640/// Run on a use-once [`Agent`].
641#[must_use]
642pub fn head<T>(uri: T) -> RequestBuilder<WithoutBody>
643where
644 Uri: TryFrom<T>,
645 <Uri as TryFrom<T>>::Error: Into<http::Error>,
646{
647 RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::HEAD, uri)
648}
649
650/// Make an OPTIONS request.
651///
652/// Run on a use-once [`Agent`].
653#[must_use]
654pub fn options<T>(uri: T) -> RequestBuilder<WithoutBody>
655where
656 Uri: TryFrom<T>,
657 <Uri as TryFrom<T>>::Error: Into<http::Error>,
658{
659 RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::OPTIONS, uri)
660}
661
662/// Make a CONNECT request.
663///
664/// Run on a use-once [`Agent`].
665#[must_use]
666pub fn connect<T>(uri: T) -> RequestBuilder<WithoutBody>
667where
668 Uri: TryFrom<T>,
669 <Uri as TryFrom<T>>::Error: Into<http::Error>,
670{
671 RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::CONNECT, uri)
672}
673
674/// Make a PATCH request.
675///
676/// Run on a use-once [`Agent`].
677#[must_use]
678pub fn patch<T>(uri: T) -> RequestBuilder<WithBody>
679where
680 Uri: TryFrom<T>,
681 <Uri as TryFrom<T>>::Error: Into<http::Error>,
682{
683 RequestBuilder::<WithBody>::new(Agent::new_with_defaults(), Method::PATCH, uri)
684}
685
686/// Make a TRACE request.
687///
688/// Run on a use-once [`Agent`].
689#[must_use]
690pub fn trace<T>(uri: T) -> RequestBuilder<WithoutBody>
691where
692 Uri: TryFrom<T>,
693 <Uri as TryFrom<T>>::Error: Into<http::Error>,
694{
695 RequestBuilder::<WithoutBody>::new(Agent::new_with_defaults(), Method::TRACE, uri)
696}
697
698#[cfg(test)]
699pub(crate) mod test {
700 use std::{io, sync::OnceLock};
701
702 use assert_no_alloc::AllocDisabler;
703 use config::{Config, ConfigBuilder};
704 use typestate::AgentScope;
705
706 use super::*;
707
708 #[global_allocator]
709 // Some tests checks that we are not allocating
710 static A: AllocDisabler = AllocDisabler;
711
712 pub fn init_test_log() {
713 static INIT_LOG: OnceLock<()> = OnceLock::new();
714 INIT_LOG.get_or_init(env_logger::init);
715 }
716
717 #[test]
718 fn connect_http_google() {
719 init_test_log();
720 let agent = Agent::new_with_defaults();
721
722 let res = agent.get("http://www.google.com/").call().unwrap();
723 assert_eq!(
724 "text/html;charset=ISO-8859-1",
725 res.headers()
726 .get("content-type")
727 .unwrap()
728 .to_str()
729 .unwrap()
730 .replace("; ", ";")
731 );
732 assert_eq!(res.body().mime_type(), Some("text/html"));
733 }
734
735 #[test]
736 #[cfg(feature = "rustls")]
737 fn connect_https_google_rustls() {
738 init_test_log();
739 use config::Config;
740
741 use crate::tls::{TlsConfig, TlsProvider};
742
743 let agent: Agent = Config::builder()
744 .tls_config(TlsConfig::builder().provider(TlsProvider::Rustls).build())
745 .build()
746 .into();
747
748 let res = agent.get("https://www.google.com/").call().unwrap();
749 assert_eq!(
750 "text/html;charset=ISO-8859-1",
751 res.headers()
752 .get("content-type")
753 .unwrap()
754 .to_str()
755 .unwrap()
756 .replace("; ", ";")
757 );
758 assert_eq!(res.body().mime_type(), Some("text/html"));
759 }
760
761 #[test]
762 #[cfg(feature = "native-tls")]
763 fn connect_https_google_native_tls_simple() {
764 init_test_log();
765 use config::Config;
766
767 use crate::tls::{TlsConfig, TlsProvider};
768
769 let agent: Agent = Config::builder()
770 .tls_config(
771 TlsConfig::builder()
772 .provider(TlsProvider::NativeTls)
773 .build(),
774 )
775 .build()
776 .into();
777
778 let mut res = agent.get("https://www.google.com/").call().unwrap();
779
780 assert_eq!(
781 "text/html;charset=ISO-8859-1",
782 res.headers()
783 .get("content-type")
784 .unwrap()
785 .to_str()
786 .unwrap()
787 .replace("; ", ";")
788 );
789 assert_eq!(res.body().mime_type(), Some("text/html"));
790 res.body_mut().read_to_string().unwrap();
791 }
792
793 #[test]
794 #[cfg(feature = "rustls")]
795 fn connect_https_google_rustls_webpki() {
796 init_test_log();
797 use crate::tls::{RootCerts, TlsConfig, TlsProvider};
798 use config::Config;
799
800 let agent: Agent = Config::builder()
801 .tls_config(
802 TlsConfig::builder()
803 .provider(TlsProvider::Rustls)
804 .root_certs(RootCerts::WebPki)
805 .build(),
806 )
807 .build()
808 .into();
809
810 agent.get("https://www.google.com/").call().unwrap();
811 }
812
813 #[test]
814 #[cfg(feature = "native-tls")]
815 fn connect_https_google_native_tls_webpki() {
816 init_test_log();
817 use crate::tls::{RootCerts, TlsConfig, TlsProvider};
818 use config::Config;
819
820 let agent: Agent = Config::builder()
821 .tls_config(
822 TlsConfig::builder()
823 .provider(TlsProvider::NativeTls)
824 .root_certs(RootCerts::WebPki)
825 .build(),
826 )
827 .build()
828 .into();
829
830 agent.get("https://www.google.com/").call().unwrap();
831 }
832
833 #[test]
834 #[cfg(feature = "rustls")]
835 fn connect_https_google_noverif() {
836 init_test_log();
837 use crate::tls::{TlsConfig, TlsProvider};
838
839 let agent: Agent = Config::builder()
840 .tls_config(
841 TlsConfig::builder()
842 .provider(TlsProvider::Rustls)
843 .disable_verification(true)
844 .build(),
845 )
846 .build()
847 .into();
848
849 let res = agent.get("https://www.google.com/").call().unwrap();
850 assert_eq!(
851 "text/html;charset=ISO-8859-1",
852 res.headers()
853 .get("content-type")
854 .unwrap()
855 .to_str()
856 .unwrap()
857 .replace("; ", ";")
858 );
859 assert_eq!(res.body().mime_type(), Some("text/html"));
860 }
861
862 #[test]
863 fn simple_put_content_len() {
864 init_test_log();
865 let mut res = put("http://httpbin.org/put").send(&[0_u8; 100]).unwrap();
866 res.body_mut().read_to_string().unwrap();
867 }
868
869 #[test]
870 fn simple_put_chunked() {
871 init_test_log();
872 let mut res = put("http://httpbin.org/put")
873 // override default behavior
874 .header("transfer-encoding", "chunked")
875 .send(&[0_u8; 100])
876 .unwrap();
877 res.body_mut().read_to_string().unwrap();
878 }
879
880 #[test]
881 fn simple_get() {
882 init_test_log();
883 let mut res = get("http://httpbin.org/get").call().unwrap();
884 res.body_mut().read_to_string().unwrap();
885 }
886
887 #[test]
888 fn simple_head() {
889 init_test_log();
890 let mut res = head("http://httpbin.org/get").call().unwrap();
891 res.body_mut().read_to_string().unwrap();
892 }
893
894 #[test]
895 fn redirect_no_follow() {
896 init_test_log();
897 let agent: Agent = Config::builder().max_redirects(0).build().into();
898 let mut res = agent
899 .get("http://httpbin.org/redirect-to?url=%2Fget")
900 .call()
901 .unwrap();
902 let txt = res.body_mut().read_to_string().unwrap();
903 #[cfg(feature = "_test")]
904 assert_eq!(txt, "You've been redirected");
905 #[cfg(not(feature = "_test"))]
906 assert_eq!(txt, "");
907 }
908
909 #[test]
910 fn redirect_max_with_error() {
911 init_test_log();
912 let agent: Agent = Config::builder().max_redirects(3).build().into();
913 let res = agent
914 .get(
915 "http://httpbin.org/redirect-to?url=%2Fredirect-to%3F\
916 url%3D%2Fredirect-to%3Furl%3D%252Fredirect-to%253Furl%253D",
917 )
918 .call();
919 let err = res.unwrap_err();
920 assert_eq!(err.to_string(), "too many redirects");
921 }
922
923 #[test]
924 fn redirect_max_without_error() {
925 init_test_log();
926 let agent: Agent = Config::builder()
927 .max_redirects(3)
928 .max_redirects_will_error(false)
929 .build()
930 .into();
931 let res = agent
932 .get(
933 "http://httpbin.org/redirect-to?url=%2Fredirect-to%3F\
934 url%3D%2Fredirect-to%3Furl%3D%252Fredirect-to%253Furl%253D",
935 )
936 .call()
937 .unwrap();
938 assert_eq!(res.status(), 302);
939 }
940
941 #[test]
942 fn redirect_follow() {
943 init_test_log();
944 let res = get("http://httpbin.org/redirect-to?url=%2Fget")
945 .call()
946 .unwrap();
947 let response_uri = res.get_uri();
948 assert_eq!(response_uri.path(), "/get")
949 }
950
951 #[test]
952 fn redirect_history_none() {
953 init_test_log();
954 let res = get("http://httpbin.org/redirect-to?url=%2Fget")
955 .call()
956 .unwrap();
957 let redirect_history = res.get_redirect_history();
958 assert_eq!(redirect_history, None)
959 }
960
961 #[test]
962 fn redirect_history_some() {
963 init_test_log();
964 let agent: Agent = Config::builder()
965 .max_redirects(3)
966 .max_redirects_will_error(false)
967 .save_redirect_history(true)
968 .build()
969 .into();
970 let res = agent
971 .get("http://httpbin.org/redirect-to?url=%2Fget")
972 .call()
973 .unwrap();
974 let redirect_history = res.get_redirect_history();
975 assert_eq!(
976 redirect_history,
977 Some(
978 vec![
979 "http://httpbin.org/redirect-to?url=%2Fget".parse().unwrap(),
980 "http://httpbin.org/get".parse().unwrap()
981 ]
982 .as_ref()
983 )
984 );
985 let res = agent
986 .get(
987 "http://httpbin.org/redirect-to?url=%2Fredirect-to%3F\
988 url%3D%2Fredirect-to%3Furl%3D%252Fredirect-to%253Furl%253D",
989 )
990 .call()
991 .unwrap();
992 let redirect_history = res.get_redirect_history();
993 assert_eq!(
994 redirect_history,
995 Some(vec![
996 "http://httpbin.org/redirect-to?url=%2Fredirect-to%3Furl%3D%2Fredirect-to%3Furl%3D%252Fredirect-to%253Furl%253D".parse().unwrap(),
997 "http://httpbin.org/redirect-to?url=/redirect-to?url=%2Fredirect-to%3Furl%3D".parse().unwrap(),
998 "http://httpbin.org/redirect-to?url=/redirect-to?url=".parse().unwrap(),
999 "http://httpbin.org/redirect-to?url=".parse().unwrap(),
1000 ].as_ref())
1001 );
1002 let res = agent.get("https://www.google.com/").call().unwrap();
1003 let redirect_history = res.get_redirect_history();
1004 assert_eq!(
1005 redirect_history,
1006 Some(vec!["https://www.google.com/".parse().unwrap()].as_ref())
1007 );
1008 }
1009
1010 #[test]
1011 fn connect_https_invalid_name() {
1012 let result = get("https://example.com{REQUEST_URI}/").call();
1013 let err = result.unwrap_err();
1014 assert!(matches!(err, Error::Http(_)));
1015 assert_eq!(err.to_string(), "http: invalid uri character");
1016 }
1017
1018 #[test]
1019 fn post_big_body_chunked() {
1020 // https://github.com/algesten/ureq/issues/879
1021 let mut data = io::Cursor::new(vec![42; 153_600]);
1022 post("http://httpbin.org/post")
1023 .content_type("application/octet-stream")
1024 .send(SendBody::from_reader(&mut data))
1025 .expect("to send correctly");
1026 }
1027
1028 #[test]
1029 #[cfg(not(feature = "_test"))]
1030 fn username_password_from_uri() {
1031 init_test_log();
1032 let mut res = get("https://martin:secret@httpbin.org/get").call().unwrap();
1033 let body = res.body_mut().read_to_string().unwrap();
1034 assert!(body.contains("Basic bWFydGluOnNlY3JldA=="));
1035 }
1036
1037 #[test]
1038 #[cfg(all(feature = "cookies", feature = "_test"))]
1039 fn store_response_cookies() {
1040 let agent = Agent::new_with_defaults();
1041 let _ = agent.get("https://www.google.com").call().unwrap();
1042
1043 let mut all: Vec<_> = agent
1044 .cookie_jar_lock()
1045 .iter()
1046 .map(|c| c.name().to_string())
1047 .collect();
1048
1049 all.sort();
1050
1051 assert_eq!(all, ["AEC", "__Secure-ENID"])
1052 }
1053
1054 #[test]
1055 #[cfg(all(feature = "cookies", feature = "_test"))]
1056 fn send_request_cookies() {
1057 init_test_log();
1058
1059 let agent = Agent::new_with_defaults();
1060 let uri = Uri::from_static("http://cookie.test/cookie-test");
1061 let uri2 = Uri::from_static("http://cookie2.test/cookie-test");
1062
1063 let mut jar = agent.cookie_jar_lock();
1064 jar.insert(Cookie::parse("a=1", &uri).unwrap(), &uri)
1065 .unwrap();
1066 jar.insert(Cookie::parse("b=2", &uri).unwrap(), &uri)
1067 .unwrap();
1068 jar.insert(Cookie::parse("c=3", &uri2).unwrap(), &uri2)
1069 .unwrap();
1070
1071 jar.release();
1072
1073 let _ = agent.get("http://cookie.test/cookie-test").call().unwrap();
1074 }
1075
1076 #[test]
1077 #[cfg(all(feature = "_test", not(feature = "cookies")))]
1078 fn partial_redirect_when_following() {
1079 init_test_log();
1080 // this should work because we follow the redirect and go to /get
1081 get("http://my-host.com/partial-redirect").call().unwrap();
1082 }
1083
1084 #[test]
1085 #[cfg(feature = "_test")]
1086 fn partial_redirect_when_not_following() {
1087 init_test_log();
1088 // this should fail because we are not following redirects, and the
1089 // response is partial before the server is hanging up
1090 get("http://my-host.com/partial-redirect")
1091 .config()
1092 .max_redirects(0)
1093 .build()
1094 .call()
1095 .unwrap_err();
1096 }
1097
1098 #[test]
1099 #[cfg(feature = "_test")]
1100 fn http_connect_proxy() {
1101 init_test_log();
1102
1103 let proxy = Proxy::new("http://my_proxy:1234/connect-proxy").unwrap();
1104
1105 let agent = Agent::config_builder()
1106 .proxy(Some(proxy))
1107 .build()
1108 .new_agent();
1109
1110 let mut res = agent.get("http://httpbin.org/get").call().unwrap();
1111 res.body_mut().read_to_string().unwrap();
1112 }
1113
1114 #[test]
1115 fn ensure_reasonable_stack_sizes() {
1116 macro_rules! ensure {
1117 ($type:ty, $size:tt) => {
1118 let sz = std::mem::size_of::<$type>();
1119 // println!("{}: {}", stringify!($type), sz);
1120 assert!(
1121 sz <= $size,
1122 "Stack size of {} is too big {} > {}",
1123 stringify!($type),
1124 sz,
1125 $size
1126 );
1127 };
1128 }
1129
1130 ensure!(RequestBuilder<WithoutBody>, 400); // 288
1131 ensure!(Agent, 100); // 32
1132 ensure!(Config, 400); // 320
1133 ensure!(ConfigBuilder<AgentScope>, 400); // 320
1134 ensure!(Response<Body>, 800); // 760
1135 ensure!(Body, 700); // 648
1136 }
1137
1138 #[test]
1139 fn limit_max_response_header_size() {
1140 init_test_log();
1141 let err = get("http://httpbin.org/get")
1142 .config()
1143 .max_response_header_size(5)
1144 .build()
1145 .call()
1146 .unwrap_err();
1147 assert!(matches!(err, Error::LargeResponseHeader(65, 5)));
1148 }
1149
1150 #[test]
1151 fn propfind_with_body() {
1152 init_test_log();
1153
1154 // https://github.com/algesten/ureq/issues/1034
1155 let request = http::Request::builder()
1156 .method("PROPFIND")
1157 .uri("https://www.google.com/")
1158 .body("Some really cool body")
1159 .unwrap();
1160
1161 let _ = Agent::config_builder()
1162 .allow_non_standard_methods(true)
1163 .build()
1164 .new_agent()
1165 .run(request)
1166 .unwrap();
1167 }
1168
1169 #[test]
1170 #[cfg(feature = "_test")]
1171 fn non_standard_method() {
1172 init_test_log();
1173 let method = Method::from_bytes(b"FNORD").unwrap();
1174
1175 let req = Request::builder()
1176 .method(method)
1177 .uri("http://httpbin.org/fnord")
1178 .body(())
1179 .unwrap();
1180
1181 let agent = Agent::new_with_defaults();
1182
1183 let req = agent
1184 .configure_request(req)
1185 .allow_non_standard_methods(true)
1186 .build();
1187
1188 agent.run(req).unwrap();
1189 }
1190
1191 // This doesn't need to run, just compile.
1192 fn _ensure_send_sync() {
1193 fn is_send(_t: impl Send) {}
1194 fn is_sync(_t: impl Sync) {}
1195
1196 // Agent
1197 is_send(Agent::new_with_defaults());
1198 is_sync(Agent::new_with_defaults());
1199
1200 // ResponseBuilder
1201 is_send(get("https://example.test"));
1202 is_sync(get("https://example.test"));
1203
1204 let data = vec![0_u8, 1, 2, 3, 4];
1205
1206 // Response<Body> via ResponseBuilder
1207 is_send(post("https://example.test").send(&data));
1208 is_sync(post("https://example.test").send(&data));
1209
1210 // Request<impl AsBody>
1211 is_send(Request::post("https://yaz").body(&data).unwrap());
1212 is_sync(Request::post("https://yaz").body(&data).unwrap());
1213
1214 // Response<Body> via Agent::run
1215 is_send(run(Request::post("https://yaz").body(&data).unwrap()));
1216 is_sync(run(Request::post("https://yaz").body(&data).unwrap()));
1217
1218 // Response<BodyReader<'a>>
1219 let mut response = post("https://yaz").send(&data).unwrap();
1220 let shared_reader = response.body_mut().as_reader();
1221 is_send(shared_reader);
1222 let shared_reader = response.body_mut().as_reader();
1223 is_sync(shared_reader);
1224
1225 // Response<BodyReader<'static>>
1226 let response = post("https://yaz").send(&data).unwrap();
1227 let owned_reader = response.into_parts().1.into_reader();
1228 is_send(owned_reader);
1229 let response = post("https://yaz").send(&data).unwrap();
1230 let owned_reader = response.into_parts().1.into_reader();
1231 is_sync(owned_reader);
1232
1233 let err = Error::HostNotFound;
1234 is_send(err);
1235 let err = Error::HostNotFound;
1236 is_sync(err);
1237 }
1238}