client.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. extern crate hyper;
  2. extern crate hyper_tls;
  3. use hyper::rt::{self, Future, Stream};
  4. use hyper::{Body, Client, Method, Request};
  5. use hyper_tls::HttpsConnector;
  6. // use std::io::{self, Write};
  7. fn main() {
  8. rt::run(rt::lazy(|| {
  9. let https = HttpsConnector::new(4).expect("TLS initialization failed");
  10. let client = Client::builder().build::<_, hyper::Body>(https);
  11. // let uri = "http://httbin.org/ip".parse().unwrap();
  12. let uri: hyper::Uri = "http://httpbin.org/post".parse().unwrap();
  13. let json = r#"{"library":"hyper"}"#;
  14. let mut req = Request::new(Body::from(json));
  15. *req.method_mut() = Method::POST;
  16. *req.uri_mut() = uri.clone();
  17. req.headers_mut().insert(
  18. hyper::header::CONTENT_TYPE,
  19. hyper::header::HeaderValue::from_static("application/json"),
  20. );
  21. //client
  22. // .get(uri)
  23. // .and_then(|res| {
  24. // println!("Response: {}", res.status());
  25. // res
  26. // .into_body()
  27. // .for_each(|chunk| {
  28. // io::stdout()
  29. // .write_all(&chunk)
  30. // .map_err(|e| {
  31. // panic!("example expects stdout is open, error={}", e)
  32. // })
  33. // })
  34. // })
  35. // .map_err(|err| {
  36. // println!("Error: {}", err);
  37. // })
  38. let post = client.request(req).and_then(|res| {
  39. println!("POST: {}", res.status());
  40. res.into_body().concat2()
  41. });
  42. let get = client
  43. .get("http://httpbin.org/headers".parse().unwrap())
  44. .and_then(|res| {
  45. println!("GET: {}", res.status());
  46. res.into_body().concat2()
  47. });
  48. let work = post.join(get);
  49. work.map(|(posted, got)| {
  50. println!("GET: {:?}", got);
  51. println!("POST: {:?}", posted);
  52. })
  53. .map_err(|err| {
  54. println!("Error: {}", err);
  55. })
  56. }))
  57. }