一个Rust HttpClient例子
jopen
9年前
在cargo.toml文件中添加
[dependencies] hyper = "0.7.2"
src中创建main.rs
extern crate hyper; use std::io::Read; use hyper::Client; fn main() { println!("welcome to rust http"); let client = Client::new(); let mut res = client.get("https://httpbin.org/get").send().unwrap(); assert_eq!(res.status, hyper::Ok); println!("headers:\n {}", res.headers); let mut body = String::new(); res.read_to_string(&mut body).unwrap(); println!("body:\n {}", body); res = client.post("https://httpbin.org/post").body("{\"a\":1}").send().unwrap(); assert_eq!(res.status, hyper::Ok); println!("headers:\n {}", res.headers); let mut body = String::new(); res.read_to_string(&mut body).unwrap(); println!("body:\n {}", body); }
执行 cargo build 后执行 ./target/debug/项目名 即可看到效果。