在rust中使用activx的简单http客户端。从服务器获取响应,可以处理头。但当试图处理有效载荷时,我对铁锈的理解失败了。我的愿望是逐字节处理有效负载,以获得巨大的流和分块数据。简单的body((解决方案运行良好。但是如何从有效负载中获取字节。它似乎是impl Stream,所以fn size_hint((是可访问的,但解压缩器impl解码器impl Stream中的poll_text不是。
main.rs
use actix::prelude::*;
use actix_http::encoding::{Decoder};
use actix_web::{HttpMessage,client::ClientBuilder,dev::Payload,http::{Version, StatusCode},web::Bytes};
use futures::future::{TryFutureExt};
use futures_core::stream::Stream;
use std::pin::Pin;
use std::boxed::Box;
use std::task::{Context, Poll};
#[actix_web::main]
async fn main() {
const URL : [&str; 2] = ["..",".."];
let client = ClientBuilder::new()
.disable_timeout()
.disable_redirects()
.header("User-Agent", "actix-web/3.0")
.header("Accept-Encoding", "gzip, deflate, br, chunked")
.header("Connection", "keepalive")
.header("DNT", "1")
.max_http_version( Version::HTTP_2 )
.finish();
// Create request builder and send request
let response =
client.get(URL[0]).send().map_err(|err|{
println!("Error on send {:?}",err);
});
match response.await{
Ok( mut v) => {
println!("encoding: {:?}",v.encoding());
println!("content type: {:?}",v.content_type());
println!("mime type: {:?}",v.mime_type());
println!("chunked: {:?}",v.chunked());
match v.status(){
StatusCode::OK => {
/* works fine
match v.body().await {
Ok(m) => { println!("body {:?}", m); },
Err(r) => { println!("Error.body {:?}",r); }
}
*/
// but what about handling byte by byte?
let payload = v.take_payload();
match payload {
Payload::None => { println!(" no data "); },
Payload::H1(h1) => {println!(" data h1 {:?}", h1); },
Payload::H2(d2) => {println!(" data h2 "); },
Payload::Stream(s1) => {
println!(" data stream ");
println!(" size: {:?}", s1.size_hint());
// Decompress impl Decoder
// Decoder impl Stream
// but how to activate poll_next
// compiler can size_hint from Stream
// but poll_next not found??
}
};
},
StatusCode::NOT_FOUND => {
println!(" resource was not found");
},
_ => {
}
}
},
Err(err) => {
println!("Error {:?}",err);
}
};
}
Payload
实现了Stream
,因此可以在块中对其进行迭代。
每个区块将是一个Result<Bytes, PayloadError>
。
// use futures::StreamExt;
let mut payload = v.take_payload();
while let Some(chunk) = payload.next().await {
// handle chunk here
}