在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);

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

正常运行:

相关推荐
Livingbody15 分钟前
Fast Whisper 语音转文本
后端
程序员岳焱21 分钟前
深度剖析:Spring AI 与 LangChain4j,谁才是 Java 程序员的 AI 开发利器?
java·人工智能·后端
G探险者27 分钟前
《深入理解 Nacos 集群与 Raft 协议》系列五:为什么集群未过半,系统就不可用?从 Raft 的投票机制说起
分布式·后端
G探险者28 分钟前
《深入理解 Nacos 集群与 Raft 协议》系列一:为什么 Nacos 集群必须过半节点存活?从 Raft 协议说起
分布式·后端
G探险者32 分钟前
《深入理解 Nacos 集群与 Raft 协议》系列四:日志复制机制:Raft 如何确保提交可靠且幂等
分布式·后端
G探险者34 分钟前
《深入理解 Nacos 集群与 Raft 协议》系列三:日志对比机制:Raft 如何防止数据丢失与错误选主
分布式·后端
G探险者34 分钟前
《深入理解 Nacos 集群与 Raft 协议》系列二:Raft 为什么要“选主”?选主的触发条件与机制详解
分布式·后端
我的golang之路果然有问题38 分钟前
云服务器部署Gin+gorm 项目 demo
运维·服务器·后端·学习·golang·gin
Java水解41 分钟前
彻底解决Flask日志重复打印问题:从原理到实践
后端·flask
Nick同学42 分钟前
GatewayWorker 使用总结
后端·php