Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

hyper

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?

like image 473
rap-2-h Avatar asked Jul 01 '16 14:07

rap-2-h


2 Answers

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

}
like image 117
JDemler Avatar answered Sep 18 '22 01:09

JDemler


Here is how to print the response status and body using tokio 0.2, hyper 0.13, and async/await syntax.

use std::error::Error;

use hyper::body;
use hyper::{Body, Client, Response};
use hyper_tls::HttpsConnector;
use tokio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
    let https = HttpsConnector::new();
    let client = Client::builder().build::<_, Body>(https);

    let res = client
        .get("https://www.reddit.com/r/programming/.rss".parse().unwrap())
        .await?;

    println!("Status: {}", res.status());

    let body_bytes = body::to_bytes(res.into_body()).await?;
    let body = String::from_utf8(body_bytes.to_vec()).expect("response was not valid utf-8");
    println!("Body: {}", body);

    Ok(())
}
like image 40
euclio Avatar answered Sep 22 '22 01:09

euclio