我正在嘗試構建一個執行異步 http 請求并回傳其回應 正文的程式。
這是回傳回應的函式的樣子:
let responses = stream::iter(urls)
.map(|line| {
let client = &client;
async move {
client.get(&line).send().await.map(|resp| {
(line, resp)
})}
})
.buffer_unordered(concurrency_amount);
但是,回傳后resp,我不能使用resp.text(),因為resp.text()是型別Future<Output=Result<String>>。
如何使函式也回傳resp.text()元組?
uj5u.com熱心網友回復:
假設您正在使用reqwest,應該可以使用 , 來收集回應正文的位元組,Response::chunk()但只需要一個可變參考。text()selfchunk()
類似下面的內容會收集回應正文并以有損方式將其解碼為字串。
use futures_util::StreamExt;
#[tokio::main]
async fn main() {
let cli = reqwest::Client::new();
let urls = vec![
"https://stackoverflow.com".to_string(),
"https://google.com".into(),
"https://tokio.rs".into(),
];
let responses = futures_util::stream::iter(urls.into_iter())
.then(|url| { // note that I replaced `map` with `then` here.
let cli = cli.clone();
async move {
let mut resp = cli.get(url.clone()).send().await.unwrap();
let mut body = Vec::new();
while let Some(chunk) = resp.chunk().await.unwrap() {
body.extend_from_slice(&*chunk);
}
(url, resp, String::from_utf8_lossy(&body).to_string())
}
})
.collect::<Vec<_>>()
.await;
for (url, response, text) in responses {
println!("url: {} status: {} text: {}", url, response.status(), text);
}
}
正如行內注釋所指出的:我將map()呼叫更改為,then()以便流產生元組,而不是以元組作為輸出的期貨。
uj5u.com熱心網友回復:
這行得通嗎?
let responses = stream::iter(urls)
.map(|line| {
let client = &client;
(async move || {
let resp = client.get(&line).send().await?;
let text = resp.text().await?;
(line, resp, text)
})()
})
.buffer_unordered(concurrency_amount);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/415004.html
標籤:
下一篇:資料接收后如何移動到下一個視圖?
