You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust使用Reqwest构建请求遇InvalidHeaderValue错误求助

问题

我是Rust新手,尝试使用Reqwest库构造包含两个自定义HTTP请求头的请求,编写了相关函数(代码如下):

async fn oauth_request(server_address: &str, user_id: &str, spoof_check_secret: &str, uid_field_name: &str) {
    let client = HTTPclient::HTTPclient::new(server_address.parse().unwrap(), uid_field_name.parse().unwrap(), spoof_check_secret.parse().unwrap());
    let request_result = client
        .send_auth_request(&String::from(user_id), &spoof_check_secret)
        .await;
    match request_result {
        Ok(response) => println!("Response: {:?}", response),
        Err(error) => {
            println!("Error: {:?}", error);
            println!("user_id: {:?}", user_id);
            println!("uid_field_name: {:?}", uid_field_name);
        },
    }
}
pub async fn send_auth_request(&self, uid: &str, spoof_check_secret: &str) -> Result<reqwest::Response, reqwest::Error> {
        let request = reqwest::Client::new()
            .post(&self.url)
            .header("Shib-Spoof-Check", spoof_check_secret)
            .header(self.uid_field_name.clone(), uid)
            .body("")
            .send()
            .await?;
        Ok(request)
    }

但请求未发送成功,得到错误输出:

Error: reqwest::Error { kind: Builder, source: http::Error(InvalidHeaderValue) }
user_id: "participant:bdd25f2c-abb9-40be-ac89-5e538dad1e70"
uid_field_name: "uid"
   >> Outcome: Success
   >> Response succeeded.

(最后两行由Rocket添加,表明端点请求已成功)

其中user_id值如上所示,Shib-Spoof-Check的值是仅含小写字母和数字的字符串,无特殊字符,请问为何这两个值会被判定为无效请求头值?

回答

问题核心出在不必要的字符串解析操作上,而非请求头值本身的合法性:

  1. 你在oauth_request函数中对uid_field_name和spoof_check_secret调用了.parse().unwrap(),但这两个参数本身就是合法字符串,不需要额外解析。如果HTTPclient::new的参数接收的是String类型,这种多余的parse会触发无意义的类型转换,甚至可能在内部生成不符合HTTP头规范的字段名类型,最终构造请求时触发InvalidHeaderValue错误。

  2. 你的user_id(含冒号)和Shib-Spoof-Check值(小写字母+数字)本身完全符合HTTP头值的规范,uid作为字段名也合法,所以错误根源不在这些内容本身。

修正方案

  • 去掉oauth_request中对uid_field_name和spoof_check_secret的parse()调用,直接转换为String传入:
let client = HTTPclient::HTTPclient::new(
    server_address.parse().unwrap(), 
    uid_field_name.to_string(), 
    spoof_check_secret.to_string()
);
  • 确保HTTPclient结构体中uid_field_name的类型为String,而非其他可能不符合IntoHeaderName trait要求的类型。

内容的提问来源于stack exchange,提问作者GTP95

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 20:34:56