Search code examples
rusthyper

Displaying the response body with Hyper only shows the size of the body


I tried to display the content (body) of an URL as text using Hyper

extern crate hyper;

use hyper::client::Client;
use std::io::Read;

fn main () {

    let client = Client::new();
    let mut s = String::new();

    let res = client.get("https://www.reddit.com/r/programming/.rss")
                    .send()
                    .unwrap()
                    .read_to_string(&mut s)
                    .unwrap();

    println!("Result: {}", res);

}

But running this script just returns the size of the body:

Result: 22871

What did I do wrong? Did I misunderstood something?


Solution

  • You are reading the result of the get into s but you are printing the result of this function, which is the number of bytes read. See the documentation for Read::read_to_string.

    Thus the code which prints the retrieved content is:

    extern crate hyper;
    
    use hyper::client::Client;
    use std::io::Read;
    
    fn main () {
    
        let client = Client::new();
        let mut s = String::new();
    
        let res = client.get("https://www.reddit.com/r/programming/.rss")
                        .send()
                        .unwrap()
                        .read_to_string(&mut s)
                        .unwrap();
    
        println!("Result: {}", s);
    
    }