gpt4 book ai didi

rest - 如何从Github API获取JSON?

转载 作者:行者123 更新时间:2023-12-03 11:47:30 24 4
gpt4 key购买 nike

我只想从以下网址获取JSON。
所以我用了这段代码:

extern crate reqwest;

fn main() -> Result<(), Box<dyn std::error::Error>> {
let res = reqwest::Client::new()
.get("https://api.github.com/users/octocat")
.send()?
.text()?;
println!("{}", res);

Ok(())
}
但我不知道如何解决该错误:
error[E0277]: the `?` operator can only be applied to values that implement `std::ops::Try`
--> src\main.rs:19:15
|
19 | let res = reqwest::Client::new()
| _______________^
20 | | .get("https://api.github.com/users/octocat")
21 | | .send()?
| |________________^ the `?` operator cannot be applied to type `impl std::future::Future`
|
= help: the trait `std::ops::Try` is not implemented for `impl std::future::Future`
= note: required by `std::ops::Try::into_result`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: could not compile `Desktop`.
但我也可以通过简单的方式获得想要的东西
curl https://api.github.com/users/octocat
我尝试添加 use std::ops::Try;,但效果不佳。

最佳答案

默认情况下,reqwest crate 可提供异步api。因此,在使用.await运算符处理错误之前,您必须先使用?。您还必须使用异步运行时,例如tokio:

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.get("https://api.github.com/users/octocat")
.send()
.await?
.json::<std::collections::HashMap<String, String>>()
.await?;
println!("{:#?}", resp);
Ok(())
}
请注意,如上所示,要使用将响应转换为json,必须在 json中启用 Cargo.toml功能:
reqwest = { version = "0.10.8", features = ["json"] }
如果您不想使用异步运行时,则可以启用阻塞的 reqwest客户端:
[dependencies]
reqwest = { version = "0.10", features = ["blocking", "json"] }
并像这样使用它:
fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::blocking::Client::new()
.get("https://api.github.com/users/octocat")
.send()?
.json::<std::collections::HashMap<String, String>>()?;
println!("{:#?}", resp);
Ok(())
}
Github的api需要其他几个配置选项。这是reqwest和github api的最小工作示例:
use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};
use serde::{Deserialize};

fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut headers = HeaderMap::new();
// add the user-agent header required by github
headers.insert(USER_AGENT, HeaderValue::from_static("reqwest"));

let resp = reqwest::blocking::Client::new()
.get("https://api.github.com/users/octocat")
.headers(headers)
.send()?
.json::<GithubUser>()?;
println!("{:#?}", resp);
Ok(())
}

// Note that there are many other fields
// that are not included for this example
#[derive(Deserialize, Debug)]
pub struct GithubUser {
login: String,
id: usize,
url: String,
r#type: String,
name: String,
followers: usize
}

关于rest - 如何从Github API获取JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64666453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com