rust - 在 Hyper 0.11 中找不到类型 `post` 的名为 `hyper::Client` 的方法

标签 rust hyper

我想使用 Hyper 来制作 HTTP 请求。调用 Client::get 工作正常,但其他方法,如 Client::postClient::head 会导致编译错误。

extern crate futures;
extern crate hyper;
extern crate tokio_core;

use std::io::{self, Write};
use futures::{Future, Stream};
use hyper::Client;
use tokio_core::reactor::Core;

fn main() {
    let mut core = Core::new().unwrap();
    let client = Client::new(&core.handle());

    let uri = "http://httpbin.org/ip".parse().unwrap();
    let work = client.post(uri).and_then(|res| {
        // if post changed to get it will work correctly
        println!("Response: {}", res.status());

        res.body("x=z")
            .for_each(|chunk| io::stdout().write_all(&chunk).map_err(From::from))
    });
    core.run(work).unwrap();
}

错误:

error[E0599]: no method named `post` found for type `hyper::Client<hyper::client::HttpConnector>` in the current scope
  --> src/main.rs:15:23
   |
15 |     let work = client.post(uri).and_then(|res| {
   |                       ^^^^

error[E0277]: the trait bound `[u8]: std::marker::Sized` is not satisfied
  --> src/main.rs:20:24
   |
20 |             .for_each(|chunk| io::stdout().write_all(&chunk).map_err(From::from))
   |                        ^^^^^ `[u8]` does not have a constant size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `[u8]`
   = note: all local variables must have a statically known size

最佳答案

错误消息没有任何 secret 。您收到错误“没有找到类型 hyper::Client 的名为 post 的方法”因为没有这样的方法

如果您查看 Client 的文档,你可以看到它所有的方法。它们都不是post

相反,您需要使用 Client::request 并传入 Request值(value)。 Request 的构造函数接受 Method表示要使用的 HTTP 方法。

use hyper::{Client, Request, Method};

fn main() {
    // ...

    let uri = "http://httpbin.org/ip".parse().unwrap();
    let req = Request::new(Method::Post, uri);

    let work = client.request(req).and_then(|res| {
        // ...
    });
}

crate documentation说:

If just starting out, check out the Guides first.

有适合​​您情况的指南:Advanced Client Usage .

关于rust - 在 Hyper 0.11 中找不到类型 `post` 的名为 `hyper::Client` 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48573070/

相关文章:

rust - 在一个 Web 服务请求中启动一个线程并在另一个请求中停止它

json - 使用 serde_json 解析对象内部的对象

rust - 我可以在 Rocket 中重复使用 Tokio Core 和 Hyper Client 吗?

rust - 为 Rust 的 hyper http crate 使用自定义传输器

rust - 有没有办法将变量绑定(bind)到 tower-http/hyper/axum 中的请求?

rust - 为什么可以在 String 上调用 Colorize trait 方法,而 String 不实现 Colorize

rust - 无法将 core::slice::Iter 解析为 core::iter::Iterator?

rust - 前奏是什么?

rust - 如何强制 `async_std`任务在rust中的单个线程上运行?

file - 如何在 Rust 中使用单一方法创建文件及其父目录?