【问题标题】:No method named `post` found for type `hyper::Client` in Hyper 0.11在 Hyper 0.11 中找不到类型为“hyper::Client”的名为“post”的方法
【发布时间】:2018-02-02 23:47:16
【问题描述】:

我想使用 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

【问题讨论】:

  • hyper::Client没有post方法!见:docs.rs/hyper/0.11.16/hyper/client/struct.Client.html#impl-2。它只有get()request()client.request(Request::new(Method::Post, uri)) 合适。
  • @daboross 看起来这是一个答案。您应该将其发布为答案,而不是评论。
  • @Boiethios 我愿意,但现在 Shepmaster 的回答在很大程度上是多余的。

标签: rust hyper


【解决方案1】:

错误信息没有什么秘密。您收到错误消息“没有为类型 hyper::Client 找到名为 post 的方法”因为没有这样的方法

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

相反,您需要使用Client::request 并传入Request 值。 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 说:

如果刚刚开始,请先查看Guides

有一个完全适合您的情况的指南:Advanced Client Usage

【讨论】:

  • 我无法使用该高级客户端使用指南实施 POST。它突然说:“请记住,在我们将未来交给核心之前,后期工作实际上不会做任何事情。”
  • @SteveB 确保您也阅读了前面的指南;据推测,高级指南建立在它之前的更简单指南的基础上。另请注意,此 Q&A 是关于 Hyper 0.11,而当前版本的 Hyper 是 0.12,为了适应未来,它做了很大的改变。
猜你喜欢
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 2018-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多