[][src]Struct ureq::Response

pub struct Response { /* fields omitted */ }

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(), into_json_deserialize() or into_string() consumes the response.

All error handling, including URL parse errors and connection errors, is done by mapping onto synthetic errors. Callers must check response.synthetic_error(), response.is_ok(), or response.error() before relying on the contents of the reader.

let response = ureq::get("https://www.google.com").call();
if let Some(error) = response.synthetic_error() {
    eprintln!("{}", error);
    return;
}

// socket is still open and the response body has not been read.

let text = response.into_string().unwrap();

// response is consumed, and body has been read.

Implementations

impl Response[src]

pub fn new(status: u16, status_text: &str, body: &str) -> Self[src]

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);

pub fn get_url(&self) -> &str[src]

The URL we ended up at. This can differ from the request url when we have followed redirects.

pub fn status_line(&self) -> &str[src]

The entire status line like: HTTP/1.1 200 OK

pub fn http_version(&self) -> &str[src]

The http version: HTTP/1.1

pub fn status(&self) -> u16[src]

The status as a u16: 200

pub fn status_text(&self) -> &str[src]

The status text: OK

pub fn header<'a>(&self, name: &'a str) -> Option<&str>[src]

The header corresponding header value for the give name, if any.

pub fn headers_names(&self) -> Vec<String>[src]

A list of the header names in this response. Lowercased to be uniform.

pub fn has<'a>(&self, name: &'a str) -> bool[src]

Tells if the response has the named header.

pub fn all<'a>(&self, name: &'a str) -> Vec<&str>[src]

All headers corresponding values for the give name, or empty vector.

pub fn ok(&self) -> bool[src]

Whether the response status is: 200 <= status <= 299

pub fn redirect(&self) -> bool[src]

pub fn client_error(&self) -> bool[src]

Whether the response status is: 400 <= status <= 499

pub fn server_error(&self) -> bool[src]

Whether the response status is: 500 <= status <= 599

pub fn error(&self) -> bool[src]

Whether the response status is: 400 <= status <= 599

pub fn synthetic(&self) -> bool[src]

Tells if this response is "synthetic".

The methods firing off requests all return a Response; there is no rust style Result.

Rather than exposing a custom error type through results, this library has opted for representing potential connection/TLS/etc errors as HTTP response codes. These invented codes are called "synthetic".

The idea is that from a library user's point of view the distinction of whether a failure originated in the remote server (500, 502) etc, or some transient network failure, the code path of handling that would most often be the same.

The specific mapping of error to code can be seen in the Error doc.

However if the distinction is important, this method can be used to tell. Also see synthetic_error() to see the actual underlying error.

// scheme that this library doesn't understand
let resp = ureq::get("borkedscheme://www.google.com").call();

// it's an error
assert!(resp.error());

// synthetic error code 400
assert_eq!(resp.status(), 400);

// tell that it's synthetic.
assert!(resp.synthetic());

pub fn synthetic_error(&self) -> &Option<Error>[src]

Get the actual underlying error when the response is "synthetic".

pub fn content_type(&self) -> &str[src]

The content type part of the "Content-Type" header without the charset.

Example:

let resp = ureq::get("https://www.google.com/").call();
assert_eq!("text/html; charset=ISO-8859-1", resp.header("content-type").unwrap());
assert_eq!("text/html", resp.content_type());

pub fn charset(&self) -> &str[src]

The character set part of the "Content-Type" header.native_tls

Example:

let resp = ureq::get("https://www.google.com/").call();
assert_eq!("text/html; charset=ISO-8859-1", resp.header("content-type").unwrap());
assert_eq!("ISO-8859-1", resp.charset());

pub fn into_reader(self) -> impl Read[src]

Turn this response into a impl Read of the body.

  1. If Transfer-Encoding: chunked, the returned reader will unchunk it and any Content-Length header is ignored.
  2. If Content-Length is set, the returned reader is limited to this byte length regardless of how many bytes the server sends.
  3. If no length header, the reader is until server stream end.

Example:

use std::io::Read;

let resp =
    ureq::get("https://ureq.s3.eu-central-1.amazonaws.com/hello_world.json")
        .call();

assert!(resp.has("Content-Length"));
let len = resp.header("Content-Length")
    .and_then(|s| s.parse::<usize>().ok()).unwrap();

let mut reader = resp.into_reader();
let mut bytes = vec![];
reader.read_to_end(&mut bytes);

assert_eq!(bytes.len(), len);

pub fn into_string(self) -> IoResult<String>[src]

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.

Example:

let resp =
    ureq::get("https://ureq.s3.eu-central-1.amazonaws.com/hello_world.json")
        .call();

let text = resp.into_string().unwrap();

assert!(text.contains("hello"));

Charset support

Requires feature ureq = { version = "*", features = ["charset"] }

Attempts to respect the character encoding of the Content-Type header and falls back to utf-8.

I.e. Content-Length: text/plain; charset=iso-8859-1 would be decoded in latin-1.

pub fn into_json(self) -> IoResult<Value>[src]

Turn this response into a (serde) JSON value of the response body.

Requires feature ureq = { version = "*", features = ["json"] }

Example:

let resp =
    ureq::get("https://ureq.s3.eu-central-1.amazonaws.com/hello_world.json")
        .call();

let json = resp.into_json().unwrap();

assert_eq!(json["hello"], "world");

pub fn into_json_deserialize<T: DeserializeOwned>(self) -> IoResult<T>[src]

Turn the body of this response into a type implementing the (serde) Deserialize trait.

Requires feature ureq = { version = "*", features = ["json"] }

Example:


#[derive(Deserialize)]
struct Hello {
    hello: String,
}

let resp =
    ureq::get("https://ureq.s3.eu-central-1.amazonaws.com/hello_world.json")
        .call();

let json = resp.into_json_deserialize::<Hello>().unwrap();

assert_eq!(json.hello, "world");

pub fn from_read(reader: impl Read) -> Self[src]

Create a response from a Read trait impl.

This is hopefully useful for unit tests.

Example:

use std::io::Cursor;

let text = "HTTP/1.1 401 Authorization Required\r\n\r\nPlease log in\n";
let read = Cursor::new(text.to_string().into_bytes());
let resp = ureq::Response::from_read(read);

assert_eq!(resp.status(), 401);

Trait Implementations

impl Debug for Response[src]

impl FromStr for Response[src]

type Err = Error

The associated error which can be returned from parsing.

fn from_str(s: &str) -> Result<Self, Self::Err>[src]

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 = s.parse::<ureq::Response>().unwrap();
assert!(resp.has("X-Forwarded-For"));
let body = resp.into_string().unwrap();
assert_eq!(body, "Hello World!!!");

impl Into<Response> for Error[src]

Auto Trait Implementations

impl !RefUnwindSafe for Response

impl Send for Response

impl Sync for Response

impl Unpin for Response

impl !UnwindSafe for Response

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> Sealed<T> for T where
    T: ?Sized

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.