在rust中使用reqwest获取响应里面的cookie,报错borrow of moved value: `response`value borrowed here after move

注意:要使用cookie,需要先开启reqwest的cookie特性

ini 复制代码
reqwest = { version = "0.12", features = ["json", "cookies"] }

为啥会报租借错误呢?说的是先move了,然后再borrowed,因为move会转移response的所有权,转移所有权之后,就不能在原实例上租借了,这是rust中的规范。那再看一下为啥这里会报租借呢?看一下response.cookies()里面的定义:

可以看到cookies上面绑定了一个生命周期`a,这个生命周期是和Response绑定的,所以当Response销毁的时候,这个cookie对应的也会销毁。

那是不是在这个cookie之前有某个地方使用并move了这个response实例?

确实是的,我在获取响应内容的时候使用了这个response实例和.text()方法,看一下这个方法里面的内容是啥?

rust 复制代码
// body methods

    /// Get the full response text.
    ///
    /// This method decodes the response body with BOM sniffing
    /// and with malformed sequences replaced with the REPLACEMENT CHARACTER.
    /// Encoding is determined from the `charset` parameter of `Content-Type` header,
    /// and defaults to `utf-8` if not presented.
    ///
    /// Note that the BOM is stripped from the returned String.
    ///
    /// # Note
    ///
    /// If the `charset` feature is disabled the method will only attempt to decode the
    /// response as UTF-8, regardless of the given `Content-Type`
    ///
    /// # Example
    ///
    /// ```
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let content = reqwest::get("http://httpbin.org/range/26")
    ///     .await?
    ///     .text()
    ///     .await?;
    ///
    /// println!("text: {content:?}");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn text(self) -> crate::Result<String> {
        #[cfg(feature = "charset")]
        {
            self.text_with_charset("utf-8").await
        }

        #[cfg(not(feature = "charset"))]
        {
            let full = self.bytes().await?;
            let text = String::from_utf8_lossy(&full);
            Ok(text.into_owned())
        }
    }

就是在这里response发生了租借,所以后面我们不能再次使用response了,那么应该怎么做呢?

就是应该先使用cookies(),然后再使用text(),这样就没有问题了,完整使用代码:

rust 复制代码
        let response = request.send().await?;
        // 先使用cookie,再使用text
        let cookies = response.cookies();
        for c in cookies {
            println!("cookies: {:?} value:{:?}", c.name(), c.value());
        }
        // 获取cookie里面的ttwid
        let body = response.text().await?;
        println!("获取的直播间HTML内容是:{}", body);

也没有报错了,可以正常运行了:

正常运行:

相关推荐
学长毕业设计3 小时前
基于springboot的云南中草药知识普及管理网站的设计与开发(源码+文档+讲解视频)
java·spring boot·后端
烂蜻蜓3 小时前
Flask入门教程(八):视图函数详解——请求处理与响应的核心
后端·python·flask
卷无止境4 小时前
当FastAPI遇上机器学习,一个脚手架工具能省下多少工夫
后端·python·fastapi
卷无止境4 小时前
Kilo CLI 到底是什么
人工智能·后端·python
coderCN4 小时前
Nodejs 响应头和请求头
后端·node.js
SamDeepThinking4 小时前
里氏替换原则的盲区:为什么符合契约的List替换依然会失败?
后端·面试·程序员
码事漫谈4 小时前
比尔·盖茨这次谈的不是模型,是账单
前端·后端
小林ixn4 小时前
从零设计一个博客系统的数据库:表结构、索引与约束的实战思考
数据库·后端·mysql
那咋乎吧5 小时前
线程上下文切换和用户态进入内核态 linux内核都发生了什么
后端