【问题标题】:Why is there type mismatch when making a POST request using hyper 0.14 over TLS?为什么在 TLS 上使用 hyper 0.14 发出 POST 请求时会出现类型不匹配?
【发布时间】:2021-09-21 00:43:03
【问题描述】:

我正在尝试使用 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<()>`

不知道我在这里做错了什么。

【问题讨论】:

    标签: rust rust-tokio hyper


    【解决方案1】:

    类型不匹配与声明的请求类型完全一致。再看client的定义:

    let client: client::Client<_, hyper::Body> = client::Client::builder().build(https);
    

    Client(称为B)的第二个类型参数代表此客户端发出的所有请求的预期主体类型。 在对request 的所有后续调用中,正文类型必须匹配。在这种情况下,它被定义为hyper::Body,这也是B 的默认类型。但是,接下来发出的请求具有 () 类型的正文值。

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 2017-02-09
      • 1970-01-01
      • 2019-09-20
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多