我正在尝试使用 hyper 构建一个 POST http 请求。我正在使用tokio_rustls
tls 构建一个 https 连接器。
我正在使用的代码是:
use hyper::{body::to_bytes, client, Body, Method, Uri,Request};
let mut http = client::HttpConnector::new();
http.enforce_http(false);
//set tls configs.
let mut tls = tokio_rustls::rustls::ClientConfig::new();
// initialize http connector
let https = hyper_rustls::HttpsConnector::from((http, tls));
//prepare client with tls settings.
let client: client::Client<_, hyper::Body> = client::Client::builder().build(https);
let fut = async move {
let req = Request::builder().method(Method::POST)
.uri("url")
.body(())
.unwrap();
let res = match client.request(req).await {
Ok(d) => d,
Method => {
println!("Invalid method");
std::process::exit(1);
}
TooLarge => {
println!("Too large");
std::process::exit(1);
}
Err(e) => {
println!("unable to post {:?} ", e);
std::process::exit(1);
}
};
println!("Status:\n{}", res.status());
println!("Headers:\n{:#?}", res.headers());
let body: Body = res.into_body();
let body = to_bytes(body)
.await
.map_err(|e| error(format!("Could not get body: {:?}", e)))?;
println!("Body:\n{}", String::from_utf8_lossy(&body));
// ...
}
我收到以下错误:
error[E0308]: mismatched types
--> examples/client.rs:116:40
|
116 | let res = match client.request(req).await {
| ^^^ expected struct `Body`, found `()`
|
= note: expected struct `hyper::Request<Body>`
found struct `hyper::Request<()>`
不知道我在这里做错了什么。
类型不匹配完全按照声明的请求类型发生。再看一下 的定义client
:
let client: client::Client<_, hyper::Body> = client::Client::builder().build(https);
Client
(称为B
)的第二个类型参数代表此客户端发出的所有请求的预期正文类型。在对 的所有后续调用中request
,主体类型必须匹配。在这种情况下,它被定义为hyper::Body
,这也是 的默认类型B
。但是,接下来发出的请求的主体值为 type ()
。
let req = Request::builder().method(Method::POST)
.uri("url")
.body(()) // <--- `()` instead of `Body`
.unwrap();
如果将来不打算在所有请求中提供一个空主体,那么相应地更改类型参数B
或让编译器自动推断它是安全的。
let client: client::Client<_, _> = client::Client::builder().build(https);
否则,另一种方法是通过函数提供一个空体Body::empty
。
let req = Request::builder().method(Method::POST)
.uri("url")
.body(hyper::Body::empty()) // it's a match now
.unwrap();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句