Skip to content

Instantly share code, notes, and snippets.

@greyblake
Created June 28, 2017 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greyblake/9ecee7d63fc0f82511a3b19ed4c7991e to your computer and use it in GitHub Desktop.
Save greyblake/9ecee7d63fc0f82511a3b19ed4c7991e to your computer and use it in GitHub Desktop.
extern crate hyper;
extern crate tokio_core;
extern crate hyper_tls;
extern crate futures;
extern crate serde_json;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use hyper::header;
use hyper::client::{Connect, HttpConnector};
use hyper::Client;
use hyper_tls::HttpsConnector;
use tokio_core::reactor::Core;
use futures::Future;
use futures::Stream;
use tokio_core::io::read_to_end;
use std::io::Read;
#[derive(Deserialize,Debug)]
struct User {
id: u32,
name: String,
email: String
}
fn main() {
let url = "https://jsonplaceholder.typicode.com/users/1";
let uri = url.parse().unwrap();
let mut core = Core::new().unwrap();
let handle = core.handle();
let connector = HttpsConnector::new(4, &handle).expect("Failed to obtain HttpsConnector");
let client = Client::configure().connector(connector).build(&handle);
let f = client.get(uri)
.and_then(|res| {
res.body().fold(Vec::new(), |mut v, chunk| {
v.extend(&chunk[..]);
futures::future::ok::<_, hyper::Error>(v)
}).and_then(|chunks| {
let body = String::from_utf8(chunks).unwrap();
futures::future::ok::<_, hyper::Error>(body)
}).and_then(|body| {
let user = serde_json::from_str::<User>(&body).unwrap();
futures::future::ok::<_, hyper::Error>(user)
})
});
let resp = core.run(f).unwrap();
//println!("resp = {:?}", resp);
println!("{:?}", resp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment