pub struct Response { /* private fields */ }
Expand description
Response instances are created as results of firing off requests.
The Response
is used to read response headers and decide what to do with the body.
Note that the socket connection is open and the body not read until one of
into_reader()
, into_json()
, or
into_string()
consumes the response.
When dropping a Response
instance, one one of two things can happen. If
the response has unread bytes, the underlying socket cannot be reused,
and the connection is closed. If there are no unread bytes, the connection
is returned to the Agent
connection pool used (notice there is always
an agent present, even when not explicitly configured by the user).
let response = ureq::get("http://example.com/").call()?;
// socket is still open and the response body has not been read.
let text = response.into_string()?;
// response is consumed, and body has been read.
Implementations§
Source§impl Response
impl Response
Sourcepub fn new(
status: u16,
status_text: &str,
body: &str,
) -> Result<Response, Error>
pub fn new( status: u16, status_text: &str, body: &str, ) -> Result<Response, Error>
Construct a response with a status, status text and a string body.
This is hopefully useful for unit tests.
Example:
let resp = ureq::Response::new(401, "Authorization Required", "Please log in")?;
assert_eq!(resp.status(), 401);
Sourcepub fn get_url(&self) -> &str
pub fn get_url(&self) -> &str
The URL we ended up at. This can differ from the request url when we have followed redirects.
Sourcepub fn http_version(&self) -> &str
pub fn http_version(&self) -> &str
The http version: HTTP/1.1
Sourcepub fn status_text(&self) -> &str
pub fn status_text(&self) -> &str
The status text: OK
The HTTP spec allows for non-utf8 status texts. This uses from_utf8_lossy to convert such lines to &str.
Sourcepub fn header(&self, name: &str) -> Option<&str>
pub fn header(&self, name: &str) -> Option<&str>
The header value for the given name, or None if not found.
For historical reasons, the HTTP spec allows for header values to be encoded using encodings like iso-8859-1. Such encodings means the values are not possible to interpret as utf-8.
In case the header value can’t be read as utf-8, this function
returns None
(while the name is visible in Response::headers_names()
).
Sourcepub fn headers_names(&self) -> Vec<String>
pub fn headers_names(&self) -> Vec<String>
A list of the header names in this response. Lowercased to be uniform.
It’s possible for a header name to be returned by this function, and
still give a None
value. See Response::header()
for an explanation
as to why.
Sourcepub fn all(&self, name: &str) -> Vec<&str>
pub fn all(&self, name: &str) -> Vec<&str>
All headers corresponding values for the give name, or empty vector.
Sourcepub fn content_type(&self) -> &str
pub fn content_type(&self) -> &str
The content type part of the “Content-Type” header without the charset.
Example:
let resp = ureq::get("http://example.com/charset/iso").call()?;
assert_eq!(resp.header("content-type"), Some("text/html; charset=ISO-8859-1"));
assert_eq!("text/html", resp.content_type());
Sourcepub fn charset(&self) -> &str
pub fn charset(&self) -> &str
The character set part of the “Content-Type”.
Example:
let resp = ureq::get("http://example.com/charset/iso").call()?;
assert_eq!(resp.header("content-type"), Some("text/html; charset=ISO-8859-1"));
assert_eq!("ISO-8859-1", resp.charset());
Sourcepub fn remote_addr(&self) -> SocketAddr
pub fn remote_addr(&self) -> SocketAddr
The socket address of the server that sent the response.
Sourcepub fn local_addr(&self) -> SocketAddr
pub fn local_addr(&self) -> SocketAddr
The local address the request was made from.
Sourcepub fn into_reader(self) -> Box<dyn Read + Send + Sync + 'static>
pub fn into_reader(self) -> Box<dyn Read + Send + Sync + 'static>
Turn this response into a impl Read
of the body.
- If
Transfer-Encoding: chunked
, the returned reader will unchunk it and anyContent-Length
header is ignored. - If
Content-Length
is set, the returned reader is limited to this byte length regardless of how many bytes the server sends. - If no length header, the reader is until server stream end.
Note: If you use read_to_end()
on the resulting reader, a malicious
server might return enough bytes to exhaust available memory. If you’re
making requests to untrusted servers, you should use .take()
to
limit the response bytes read.
Example:
use std::io::Read;
let resp = ureq::get("http://httpbin.org/bytes/100")
.call()?;
assert!(resp.has("Content-Length"));
let len: usize = resp.header("Content-Length")
.unwrap()
.parse()?;
let mut bytes: Vec<u8> = Vec::with_capacity(len);
resp.into_reader()
.take(10_000_000)
.read_to_end(&mut bytes)?;
assert_eq!(bytes.len(), len);
Sourcepub fn into_string(self) -> Result<String>
pub fn into_string(self) -> Result<String>
Turn this response into a String of the response body. By default uses utf-8
,
but can work with charset, see below.
This is potentially memory inefficient for large bodies since the
implementation first reads the reader to end into a Vec<u8>
and then
attempts to decode it using the charset.
If the response is larger than 10 megabytes, this will return an error.
Example:
let text = ureq::get("http://httpbin.org/get?success")
.call()?
.into_string()?;
assert!(text.contains("success"));
§Charset support
If you enable feature ureq = { version = "*", features = ["charset"] }
, into_string()
attempts to respect the character encoding of the Content-Type
header. If there is no
Content-Type header, or the Content-Type header does not specify a charset, into_string()
uses utf-8
.
I.e. Content-Type: text/plain; charset=iso-8859-1
would be decoded in latin-1.
Sourcepub fn into_json<T: DeserializeOwned>(self) -> Result<T>
Available on crate feature json
only.
pub fn into_json<T: DeserializeOwned>(self) -> Result<T>
json
only.Read the body of this response into a serde_json::Value, or any other type that implements the serde::Deserialize trait.
You must use either a type annotation as shown below (message: Message
), or the
turbofish operator (::<Type>
) so Rust knows what type you are trying to read.
Example:
// This import requires the `derive` feature on `serde`.
// Put this in Cargo.toml: serde = { version = "1", features = ["derive"] }
use serde::{Deserialize};
#[derive(Deserialize)]
struct Message {
text: String,
}
let message: Message =
ureq::get("http://example.com/get/hello_world.json")
.call()?
.into_json()?;
assert_eq!(message.text, "Ok");
Or, if you don’t want to define a struct to read your JSON into, you can
use the convenient serde_json::Value
type to parse arbitrary or unknown
JSON.
let json: serde_json::Value = ureq::get("http://example.com/get/hello_world.json")
.call()?
.into_json()?;
assert_eq!(json["text"], "Ok");
Trait Implementations§
Source§impl<T: AsRef<[u8]> + Send + Sync + 'static> From<Response<T>> for Response
Available on crate feature http-interop
only.
impl<T: AsRef<[u8]> + Send + Sync + 'static> From<Response<T>> for Response
http-interop
only.Converts an http::Response
into a Response
.
As an http::Response
does not contain a URL, "https://example.com/"
is used as a
placeholder. Additionally, if the response has a header which cannot be converted into
the ureq equivalent, it will be skipped rather than having the conversion fail. The remote
address property will also always be 127.0.0.1:80
for similar reasons to the URL.
let http_response = http::Response::builder().status(200).body("<response>")?;
let response: ureq::Response = http_response.into();
Source§impl<T: AsRef<[u8]> + Send + Sync + 'static> From<Response<T>> for Response
Available on crate feature http-crate
only.
impl<T: AsRef<[u8]> + Send + Sync + 'static> From<Response<T>> for Response
http-crate
only.Converts an http::Response
into a Response
.
As an http::Response
does not contain a URL, "https://example.com/"
is used as a
placeholder. Additionally, if the response has a header which cannot be converted to ureq’s
internal header representation, it will be skipped rather than having the conversion fail.
The remote address property will also always be 127.0.0.1:80
for similar reasons to the URL.
let http_response = http::Response::builder().status(200).body("<response>")?;
let response: ureq::Response = http_response.into();
Source§impl From<Response> for Response<Box<dyn Read + Send + Sync + 'static>>
Available on crate feature http-interop
only.
impl From<Response> for Response<Box<dyn Read + Send + Sync + 'static>>
http-interop
only.Converts a Response
into an http::Response
, where the body is a reader containing the
body of the response.
use std::io::Read;
let response = ureq::get("http://example.com").call()?;
let http_response: http::Response<Box<dyn Read + Send + Sync + 'static>> = response.into();
Source§impl From<Response> for Response<Box<dyn Read + Send + Sync + 'static>>
Available on crate feature http-crate
only.
impl From<Response> for Response<Box<dyn Read + Send + Sync + 'static>>
http-crate
only.Converts a Response
into an http::Response
, where the body is a reader containing the
body of the response.
use std::io::Read;
let response = ureq::get("http://example.com").call()?;
let http_response: http::Response<Box<dyn Read + Send + Sync + 'static>> = response.into();
Source§impl From<Response> for Response<String>
Available on crate feature http-interop
only.
impl From<Response> for Response<String>
http-interop
only.Converts a Response
into an http::Response
, where the body is a String.
let response = ureq::get("http://example.com").call()?;
let http_response: http::Response<String> = response.into();
Source§impl From<Response> for Response<String>
Available on crate feature http-crate
only.
impl From<Response> for Response<String>
http-crate
only.Converts a Response
into an http::Response
, where the body is a String.
let response = ureq::get("http://example.com").call()?;
let http_response: http::Response<String> = response.into();
Source§impl From<Response> for Response<Vec<u8>>
Available on crate feature http-interop
only.
impl From<Response> for Response<Vec<u8>>
http-interop
only.Converts a Response
into an http::Response
, where the body is a Vec<u8>
.
let response = ureq::get("http://example.com").call()?;
let http_response: http::Response<Vec<u8>> = response.into();
Source§impl From<Response> for Response<Vec<u8>>
Available on crate feature http-crate
only.
impl From<Response> for Response<Vec<u8>>
http-crate
only.Converts a Response
into an http::Response
, where the body is a Vec<u8>
.
let response = ureq::get("http://example.com").call()?;
let http_response: http::Response<Vec<u8>> = response.into();
Source§impl FromStr for Response
impl FromStr for Response
Source§fn from_str(s: &str) -> Result<Self, Self::Err>
fn from_str(s: &str) -> Result<Self, Self::Err>
Parse a response from a string.
Example:
let s = "HTTP/1.1 200 OK\r\n\
X-Forwarded-For: 1.2.3.4\r\n\
Content-Type: text/plain\r\n\
\r\n\
Hello World!!!";
let resp: ureq::Response = s.parse()?;
assert!(resp.has("X-Forwarded-For"));
let body = resp.into_string()?;
assert_eq!(body, "Hello World!!!");