在Rust中使用hyper、tokio和futures设置HTTP请求的超时时间,可以通过以下步骤实现:
[dependencies]
hyper = "0.14"
tokio = { version = "1", features = ["full"] }
futures = "0.3"
use hyper::{Body, Client, Request};
use hyper::client::HttpConnector;
use hyper::header::HeaderValue;
use hyper::http::uri::Uri;
use hyper::http::response::Parts;
use hyper::http::StatusCode;
use hyper::service::{make_service_fn, service_fn};
use std::convert::Infallible;
use std::net::SocketAddr;
use std::time::Duration;
use tokio::time::timeout;
async fn send_request_with_timeout(uri: Uri) -> Result<Parts, Box<dyn std::error::Error + Send + Sync>> {
let client = Client::new();
let req = Request::builder()
.uri(uri)
.header("User-Agent", HeaderValue::from_static("Rust Hyper Client"))
.body(Body::empty())?;
let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap(); // 替换为实际的服务器地址
let make_service = make_service_fn(move |_| {
let client = client.clone();
async move {
Ok::<_, Infallible>(service_fn(move |req| {
let client = client.clone();
async move {
let res = client.request(req).await?;
Ok::<_, Infallible>(res)
}
}))
}
});
let timeout_duration = Duration::from_secs(5); // 设置超时时间为5秒
let response = timeout(timeout_duration, async {
let conn = HttpConnector::new();
let service = make_service;
let res = hyper::Server::bind(&addr).serve(service).await?;
Ok::<_, Infallible>(res)
})
.await?;
let (parts, _) = response.into_parts();
Ok(parts)
}
#[tokio::main]
async fn main() {
let uri: Uri = "http://example.com".parse().unwrap(); // 替换为实际的请求URL
match send_request_with_timeout(uri).await {
Ok(parts) => {
if parts.status == StatusCode::OK {
println!("Request succeeded!");
} else {
println!("Request failed with status code: {}", parts.status);
}
}
Err(err) => {
println!("Request failed with error: {}", err);
}
}
}
这样,你就可以在Rust中使用hyper、tokio和futures设置HTTP请求的超时时间了。请注意,上述代码仅为示例,实际使用时需要根据具体情况进行适当修改。
领取专属 10元无门槛券
手把手带您无忧上云