我想使用reqwest,但我不能--我有一个错误:
let users: Vec<User> = response.json();
^^^^ method not found in `Result<reqwest::blocking::Response, reqwest::Error>这是我的密码:
use reqwest::Error;
use tokio;
#[derive(Deserialize, Debug)]
struct User {
origin: String
}
#[tokio::main]
pub fn main() {
let request_url = format!("https://api.ipify.org");
println!("{}", request_url);
let response = reqwest::blocking::get(&request_url);
let users: Vec<User> = response.json();
println!("{:?}", users);
}我的依赖关系:
[dependencies]
serde = { version = "1.0.136", features = ["derive"]}
reqwest = { version = "0.11.9", features = ["blocking", "json"]}
tokio = { version = "1.17.0", features = ["full"] }为什么会发生这种事?我该怎么做才能解决这个问题?
发布于 2022-02-18 00:20:35
reqwest::blocking::get()返回一个reqwest::Result<Response>,它是内置Result类型的别名。Result表示一个可能失败的操作,因此您不一定有响应--您可能会有一个错误。
您需要使用?运算符将错误从函数中传播出去,也可以使用match或if let来展开值。
例如,使用match
let response = match reqwest::blocking::get(&request_url) {
// Unwraps the response value from the Result
Ok(r) => r,
// Unwraps the error from the Result and terminates main()
Err(err) => {
println!("Request failed: {}", err.to_string());
return;
},
};进一步读:
https://stackoverflow.com/questions/71165876
复制相似问题