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

如何在Rust中发送超过65535字符的GET请求?

解决Rust中发送大型GET请求的Uri过长问题

方案一:改用POST请求(推荐,符合HTTP规范且适配OSRM)

OSRM服务器支持通过POST请求传递大型参数获取距离矩阵,这是官方针对长参数场景的推荐方案,可完全规避Uri长度限制:

  1. 用异步HTTP客户端(如reqwest)构造POST请求,将原本放在URL中的参数(如坐标列表)移入请求体:
use reqwest::Client;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    // 构造OSRM table API所需的请求体
    let request_body = json!({
        "coordinates": [
            [13.4050, 52.5200], // 示例坐标
            [13.4280, 52.5136],
            // 更多坐标...
        ],
        "sources": [0],
        "destinations": [1, 2]
    });

    let response = client
        .post("http://your-osrm-server/table/v1/driving/")
        .json(&request_body)
        .send()
        .await?;

    let result = response.text().await?;
    println!("{}", result);
    Ok(())
}

注:需确保你的OSRM服务器版本(v5.10+)支持POST请求的table API。

方案二:绕过hyper的Uri长度限制(仅当必须用GET时)

若业务强制要求使用GET请求,可手动构建Uri并调整hyper的长度限制:

  1. 使用http::uri::Builder自定义最大长度:
use http::uri::{Builder, Scheme, Authority, PathAndQuery};
use reqwest::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    // 构造超长查询字符串
    let long_query = "your_extremely_long_query_string_here";
    // 自定义Uri,设置更大的长度限制(示例设为65536字节)
    let uri = Builder::new()
        .scheme(Scheme::HTTP)
        .authority(Authority::from_static("your-osrm-server"))
        .path_and_query(PathAndQuery::from_str(&format!("/table/v1/driving/?{}", long_query))?)
        // 覆盖默认的8192字节限制
        .max_len(65536)
        .build()?;

    let response = client.get(uri).send().await?;
    let result = response.text().await?;
    println!("{}", result);
    Ok(())
}

注:该方法依赖hyper的API,未来版本可能存在变动,需确认客户端支持传入http::Uri类型参数(reqwest支持)。

方案三:使用不依赖hyper的异步HTTP客户端

若上述方案均不满足需求,可尝试使用不基于hyper的异步客户端(如实验性异步支持的ureq或async-h1),但这类客户端生态不如基于hyper的成熟,需权衡利弊。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:01:42