「 libcurl 的 Rust 绑定库 」
翻译的原文 | 与日期 | 最新更新 | 更多 |
---|---|---|---|
commit | ⏰ 2018-11-07 | 中文翻译 |
欢迎 👏 勘误/校对/更新贡献 😊 具体贡献请看
If help, buy me coffee —— 营养跟不上了,给我来瓶营养快线吧! 💰
Rust 绑定 libcurl
extern crate curl;
use std::io::{stdout, Write};
use curl::easy::Easy;
// 打印一个 web页面 到 stdout
fn main() {
let mut easy = Easy::new();
easy.url("https://www.rust-lang.org/").unwrap();
easy.write_function(|data| {
stdout().write_all(data).unwrap();
Ok(data.len())
}).unwrap();
easy.perform().unwrap();
println!("{}", easy.response_code().unwrap());
}
extern crate curl;
use curl::easy::Easy;
// 捕获 output(web页面) 到 一个本地变量 `Vec`.
fn main() {
let mut dst = Vec::new();
let mut easy = Easy::new();
easy.url("https://www.rust-lang.org/").unwrap();
let mut transfer = easy.transfer();
transfer.write_function(|data| {
dst.extend_from_slice(data);
Ok(data.len())
}).unwrap();
transfer.perform().unwrap();
}
Easy
的这个put
和post
方法,可以配置 HTTP 请求,然后read_function
可以用来填充指定的数据。该接口与实现Read
的类型匹配。
extern crate curl;
use std::io::Read;
use curl::easy::Easy;
fn main() {
let mut data = "this is the body".as_bytes();
let mut easy = Easy::new();
easy.url("http://www.example.com/upload").unwrap();
easy.post(true).unwrap();
easy.post_field_size(data.len() as u64).unwrap();
let mut transfer = easy.transfer();
transfer.read_function(|buf| {
Ok(data.read(buf).unwrap_or(0))
}).unwrap();
transfer.perform().unwrap();
}
自定义的 headers,可以指定为请求的一部分:
extern crate curl;
use curl::easy::{Easy, List};
fn main() {
let mut easy = Easy::new();
easy.url("http://www.example.com").unwrap();
let mut list = List::new();
list.append("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==").unwrap();
easy.http_headers(list).unwrap();
easy.perform().unwrap();
}
handle
(下面的变量)可以跨多个请求重复使用。Curl 将试图保持连接活着.
extern crate curl;
use curl::easy::Easy;
fn main() {
let mut handle = Easy::new();
handle.url("http://www.example.com/foo").unwrap();
handle.perform().unwrap();
handle.url("http://www.example.com/bar").unwrap();
handle.perform().unwrap();
}
libcurl 库通过"multi"接口,支持同时发送多个请求。位于当前curl-rust
下的multi
模块中。其提供同时执行多个传输的能力。有关更多信息,请参见multi
模块.
默认情况下,此箱子(crate)将尝试动态链接到,在系统范围内的 libcurl 和 SSL 库。一些行为可通过各种 Cargo 功能定制:
名 | 曰 |
---|---|
ssl |
启用 SSL 支持。默认启用. |
http2 |
通过 libnghttp2 启用 HTTP/2 支持。默认情况下禁用. |
static-curl |
使用捆绑的 libcurl 版本并静态链接到它。默认情况下禁用. |
static-ssl |
使用捆绑的 OpenSSL 版本并静态链接到它。只适用于使用 OpenSSL 的平台。默认情况下禁用. |
spengo |
启用 SPEGNO 支持。默认情况下禁用. |
此绑定库已经使用 Curl 版本 7.24.0 开发。它们应该与任何新版本的 curl 一起工作,并且可能与旧版本一起工作,但是这还没有经过测试.
这个curl-rust
,MIT 许可证,见LICENSE
更多细节.