Merge pull request #219 from knight42/response-text

Add Response::text()
This commit is contained in:
Sean McArthur
2017-10-30 12:23:59 -07:00
committed by GitHub
2 changed files with 55 additions and 2 deletions

View File

@@ -165,6 +165,26 @@ impl Response {
serde_json::from_reader(self).map_err(::error::from) serde_json::from_reader(self).map_err(::error::from)
} }
/// Get the response text.
///
/// # Example
///
/// ```rust
/// # extern crate reqwest;
/// # fn run() -> Result<(), Box<::std::error::Error>> {
/// let content = reqwest::get("http://httpbin.org/range/26")?.text()?;
/// # Ok(())
/// # }
/// ```
pub fn text(&mut self) -> ::Result<String> {
let len = self.headers().get::<::header::ContentLength>()
.map(|ct_len| **ct_len)
.unwrap_or(0);
let mut content = String::with_capacity(len as usize);
self.read_to_string(&mut content).map_err(::error::from)?;
Ok(content)
}
/// Copy the response body into a writer. /// Copy the response body into a writer.
/// ///
/// This function internally uses [`std::io::copy`] and hence will continuously read data from /// This function internally uses [`std::io::copy`] and hence will continuously read data from
@@ -185,10 +205,10 @@ impl Response {
/// # } /// # }
/// ``` /// ```
#[inline] #[inline]
pub fn copy_to<W: ?Sized>(&mut self, w: &mut W) -> io::Result<u64> pub fn copy_to<W: ?Sized>(&mut self, w: &mut W) -> ::Result<u64>
where W: io::Write where W: io::Write
{ {
io::copy(self, w) io::copy(self, w).map_err(::error::from)
} }
/// Turn a response into an error if the server returned an error. /// Turn a response into an error if the server returned an error.

View File

@@ -5,6 +5,39 @@ mod support;
use std::io::Read; use std::io::Read;
#[test]
fn test_response_text() {
let server = server! {
request: b"\
GET /text HTTP/1.1\r\n\
Host: $HOST\r\n\
User-Agent: $USERAGENT\r\n\
Accept: */*\r\n\
Accept-Encoding: gzip\r\n\
\r\n\
",
response: b"\
HTTP/1.1 200 OK\r\n\
Server: test\r\n\
Content-Length: 5\r\n\
\r\n\
Hello\
"
};
let url = format!("http://{}/text", server.addr());
let mut res = reqwest::get(&url).unwrap();
assert_eq!(res.url().as_str(), &url);
assert_eq!(res.status(), reqwest::StatusCode::Ok);
assert_eq!(res.headers().get(),
Some(&reqwest::header::Server::new("test".to_string())));
assert_eq!(res.headers().get(),
Some(&reqwest::header::ContentLength(5)));
let body = res.text().unwrap();
assert_eq!(b"Hello", body.as_bytes());
}
#[test] #[test]
fn test_response_copy_to() { fn test_response_copy_to() {
let server = server! { let server = server! {