如何发出 GET 请求并打印结果?

How do you issue a GET request and print the results?

我想将带有 api 键的 https 字符串传递给 Rust 并打印出 GET 请求的结果。

#[macro_use]
extern crate serde_json;
extern crate reqwest;

use reqwest::Error;
use std::future::Future;

#[derive(Debug)]
fn main() -> Result<(), Error> {
 
  //Testing out pretty print JSON
  let obj = json!({"data":{"updated_at":"2021-09-17T17:41:05.677631986Z","items":[{"signed_at":"2015-07-30T03:26:13Z","height":0}],"pagination":null},"error":false,"error_message":null,"error_code":null});
  
  //Pretty print the above JSON
  //This works
  println!("{}", serde_json::to_string_pretty(&obj).unwrap());

  //Issue API GET request
  //Colon at the end of my_private_key is to bypass the password
  let request_url = format!("https://api.xyz.com/v1/1/ -u my_private_key:");

  let response = reqwest::get(&request_url);

  println!("{:?}", response);

  Ok(())

}

我从编译器收到以下输出。

--> src/main.rs:19:22
 |
19 |     println!("{:?}", response);
 |                      ^^^^^^^^ `impl Future` cannot be formatted using `{:?}` because it doesn't implement `Debug`
 |
 = help: the trait `Debug` is not implemented for `impl Future`
 = note: required by `std::fmt::Debug::fmt`
 = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

reqwest::get() 是一个 异步函数 而它 returns 是一个 未来 。 Future 表示将来要完成的任务。如果您在异步函数中,则可以使用 await 在 future 完成后继续并获得结果。如:

let response = reqwest::get("https://example.com").await;

main 默认情况下不能异步,但您可以使用 tokio crate 并用 #[tokio::main].

注释 main