跳至正文

HTTP 客户端 ​

简介 ​

Laravel 的 HTTP 客户端基于 reqwest,方便你向外部 API 和 Web 服务发送请求。它内置超时时间、可配置的重试和错误处理,也支持在测试中模拟响应,使测试套件无需访问网络。

所有客户端函数和类型都位于 laravel::http::client 模块。

发送请求 ​

使用 get、post、put、patch、delete 或 head 构建请求,按需链式设置选项,再等待结果:

rust
use laravel::http::client;

let response = client::get("https://example.com/users").await?;

等待时会发出请求,并读取完整响应体。即使 HTTP 状态码为 404 或 500,仍会返回 Ok(response);只有请求无法发送或超时才会导致 ? 失败。要自动将非 2xx 状态转换为错误,请参阅错误处理。

你可以在处理器、控制台命令、队列任务及监听器中发送请求。自行创建任务时,请使用 laravel::task::spawn 使其继承应用的 HTTP 客户端上下文。tokio::spawn 无法传递该上下文。

响应 ​

Response 提供以下方法来检查服务器的响应:

方法返回值
status()StatusCode,可直接与整数比较(response.status() == 404)。
successful()状态码为 2xx 时返回 true。
redirect()状态码为 3xx 时返回 true。
failed()状态码为 4xx 或 5xx 时返回 true。
client_error()、server_error()分别在状态码为 4xx、5xx 时返回 true。
header("x-name")以 Option<&str> 返回响应头的值。
headers()以 &HeaderMap 返回全部响应头。
url()跟随重定向后的最终 URL。
bytes()、text()以 &Bytes 或 &str 返回响应体。
json::<T>()将 JSON 响应体反序列化为 Result<T, Error>。

请求完成时,响应体已全部缓冲,因此 json() 和 text() 都是同步方法。可以将 JSON 解码为自己的结构体,只需要少数字段时也可以解码为 serde_json::Value:

rust
use laravel::http::client;
use serde::Deserialize;

#[derive(Deserialize)]
pub struct GitHubUser {
    pub login: String,
    pub name: String,
}

let user: GitHubUser = client::get("https://api.github.com/users/taylorotwell")
    .await?
    .json()?;

let raw: serde_json::Value = client::get("https://api.github.com/users/taylorotwell")
    .await?
    .json()?;

let name = &raw["name"];

请求数据 ​

使用 json 可以将任意实现了 Serialize 的值作为 JSON 请求体发送:

rust
use laravel::http::client;
use serde_json::json;

client::post("https://example.com/users")
    .json(json!({ "name": "Steve", "role": "Network Administrator" }))
    .await?;

使用 query 可以从键值对、json! 对象或 Serialize 结构体追加查询参数(值为 None 的字段自动省略):

rust
use laravel::http::client;
use serde::Serialize;
use serde_json::json;

client::get("https://example.com/users")
    .query([("name", "Taylor"), ("role", "admin")])
    .await?;

client::get("https://example.com/users")
    .query(json!({ "name": "Taylor", "page": 2 }))
    .await?;

#[derive(Serialize)]
struct Search {
    q: String,
    page: u32,
    sort: Option<String>,
}

client::get("https://example.com/search")
    .query(Search {
        q: "laravel".into(),
        page: 2,
        sort: None,
    })
    .await?;

Rust 数组要求元素类型一致。如果参数值的类型不同,可以使用 json! 或 Serialize 结构体,或多次链式调用 .query(..)。

使用 form 发送 URL 编码的表单,使用 body 发送带显式内容类型的原始请求体,或使用 body_file 从磁盘流式发送文件,避免将文件缓存在内存中:

rust
client::post("https://example.com/users")
    .form([("name", "Sara"), ("role", "Privacy Consultant")])
    .await?;

client::put("https://example.com/notes/1")
    .body("Remember the milk.", "text/plain")
    .await?;

client::put("https://example.com/backups/latest")
    .body_file("storage/app/backup.zip", "application/zip")
    .await?;

附加文件 ​

使用 attach 上传 multipart 文件,传入表单字段名和 Attachment。所有 form 字段都会与附件一同发送:

rust
use laravel::http::client::{self, Attachment};

client::post("https://example.com/reports")
    .attach("report", Attachment::from_path("storage/app/reports/q3.pdf"))
    .form([("quarter", "Q3")])
    .await?;

Attachment::from_path 从磁盘流式读取文件,相对路径基于应用的基础路径解析。Attachment::from_data(bytes, "avatar.png") 使用指定文件名发送内存中的字节。默认根据文件名推断内容类型,也可以用 named 和 mime 覆盖文件名或 MIME 类型:

rust
Attachment::from_path("storage/app/exports/1234.tmp")
    .named("export.csv")
    .mime("text/csv")

还可以直接在处理器中转发收到的 UploadedFile:

rust
use laravel::http::{UploadedFile, client};
use laravel::prelude::*;

#[laravel::input]
#[validate(authenticated)]
pub struct StorePhoto {
    #[validate(required, image)]
    photo: UploadedFile,
}

pub async fn store(Valid(form): Valid<StorePhoto>) -> laravel::Result<Redirect> {
    client::post("https://storage.example.com/photos")
        .attach("photo", &form.photo)
        .await?;

    Ok(Redirect::back())
}

转发上传文件应当在请求处理器内完成,因为 Laravel 会在请求结束时清理临时上传文件,队列任务或后台任务届时可能无法访问它们。

请求头 ​

使用 header 添加单个请求头,使用 headers 批量添加。设置同名请求头会替换先前的值:

rust
use laravel::http::client;
use serde_json::json;

client::post("https://example.com/users")
    .headers([("x-tenant", "acme"), ("x-locale", "en")])
    .header("idempotency-key", "user-1234")
    .json(json!({ "name": "Taylor" }))
    .await?;

使用 accept 或简写 accept_json 设置 Accept 请求头:

rust
client::get("https://example.com/users").accept_json().await?;

client::get("https://example.com/reports/monthly")
    .accept("text/csv")
    .await?;

身份认证 ​

对外请求支持 Bearer 令牌和 HTTP 基本认证。要将 Bearer 令牌加到请求的 Authorization 头中(Authorization: Bearer <token>),请调用 token:

rust
use laravel::http::client;

let response = client::get("https://api.github.com/user")
    .token("your-token")
    .await?;

通过 basic_auth 设置 HTTP 基本认证凭据,它会将用户名和密码用 Base64 编码后放入 Authorization: Basic 请求头:

rust
use laravel::http::client;

let response = client::get("https://example.com/user")
    .basic_auth("taylor@laravel.com", "secret")
    .await?;

对于要求自定义认证方式或 API 密钥请求头的 API,请用 header 直接传入相应的头:

rust
use laravel::http::client;

let response = client::get("https://api.example.com/events")
    .header("x-api-key", "your-api-key")
    .await?;

在生产应用中,请将 API 密钥和令牌放入自定义配置节,再向处理器或服务注入该配置节,避免将凭据写入源代码:

rust
// src/config/services.rs
use laravel::config::Section;

#[derive(Clone, Section)]
pub struct GitHub {
    #[env("GITHUB_TOKEN", required)]
    pub token: String,
}
rust
use laravel::config::Section;
use laravel::http::client;

use crate::config::services::GitHub;

pub async fn show(github: Section<GitHub>) -> laravel::Result<String> {
    let response = client::get("https://api.github.com/user")
        .token(&github.token)
        .await?;

    Ok(response.text().into_owned())
}

Laravel 自动将 Authorization、Proxy-Authorization 和 Cookie 请求头的值标记为敏感,以便在调试输出中隐藏。

基础 URL 和可复用请求 ​

在多处调用同一 API 时,可以通过 client::base_url 构建可复用的 PendingRequest 模板。统一配置共享请求头、令牌和错误处理,然后通过 get、post 等方法传入相对路径:

rust
use laravel::config::Section;
use laravel::http::client::{self, PendingRequest};
use laravel::prelude::*;
use serde_json::json;

use crate::config::services::GitHub;

fn github(config: &GitHub) -> PendingRequest {
    client::base_url("https://api.github.com")
        .token(&config.token)
        .accept_json()
        .ensure_successful()
}

pub async fn show(config: Section<GitHub>) -> laravel::Result<Json<serde_json::Value>> {
    let github = github(&config);

    let user: serde_json::Value = github.get("/user").await?.json()?;

    let repositories: serde_json::Value = github
        .get("/user/repos")
        .query([("per_page", 100)])
        .await?
        .json()?;

    Ok(Json(json!({ "user": user, "repositories": repositories })))
}

URL 参数 ​

请避免用 format! 直接将用户输入插入 URL,../admin 等值可能改变目标路径。使用 {name} 占位符并通过 url_parameters 传值,它会对每个参数进行百分号编码,使其作为一个独立路径段使用:

rust
use laravel::http::client;

client::get("https://api.github.com/repos/{owner}/{repo}")
    .url_parameters([("owner", "laravel"), ("repo", "framework")])
    .await?;

url_parameters 与 query 类似,接受键值对或 Serialize 结构体。要展开完整基础 URL 等无需按路径段编码的参数,请使用 {+name}。

超时 ​

默认情况下,完整响应的等待上限为 30 秒,建立连接的上限为 10 秒。可用 timeout 覆盖单个请求的限制:

rust
use laravel::http::client;
use laravel::prelude::*;

client::get("https://example.com").timeout(3.seconds()).await?;

请求超时时返回 Error::Connection,其 error.is_timeout() 为 true。要更改整个应用的默认值,请配置客户端。

重试 ​

要在连接失败或收到非 2xx 响应时自动重试,请调用 retry。传入最大尝试次数,以及固定的等待时长或 Backoff::exponential 退避策略:

rust
use laravel::http::client::{self, Backoff};
use laravel::prelude::*;
use serde_json::json;

client::post("https://example.com/webhooks")
    .json(json!({ "event": "order.shipped" }))
    .retry(3, 100.milliseconds())
    .await?;

client::get("https://example.com")
    .retry(5, Backoff::exponential(100.milliseconds())) // 100ms, 200ms, 400ms, 800ms
    .await?;

所有尝试都失败时,客户端会返回最后一次尝试的错误。

如果 429 或 503 响应包含 Retry-After 头(值为秒数或 HTTP 日期),只要等待时间未超出请求超时限制或 total_timeout,Laravel 就会至少等待指定时间后再试。如果延迟超过剩余时间,客户端会立即停止重试并返回错误,供你处理或重新将任务入队。

每次尝试都有独立的超时限制,多次重试的总耗时可能超出处理器可接受的延迟。使用 total_timeout 可以限制所有尝试和退避等待的总时长:

rust
use laravel::http::client::{self, Backoff};
use laravel::prelude::*;

client::get("https://api.github.com/users/taylorotwell")
    .timeout(2.seconds())
    .retry(5, Backoff::exponential(200.milliseconds()))
    .total_timeout(5.seconds())
    .await?;

使用 total_timeout(5.seconds()) 后,只要总预算还剩 3 秒,即使每次尝试的上限是 2 秒,也会遵守 3 秒的 Retry-After;若 Retry-After 为 24 小时,则立即返回失败。

要只对特定错误重试,请向 retry_when 传入判断函数(尝试次数从 1 起算):

rust
use laravel::http::client::{self, Error};
use laravel::prelude::*;

client::get("https://example.com")
    .retry(3, 100.milliseconds())
    .retry_when(|error, _attempt| matches!(error, Error::Connection(_)))
    .await?;

警告

重试会再次发送相同的 HTTP 请求。只应重试幂等操作或受幂等键保护的请求。

错误处理 ​

默认情况下,4xx 和 5xx 响应均返回 Ok(response)。调用 ensure_successful 可以将任何非 2xx 状态转换为 Error::Status:

rust
use laravel::http::client;

let user: serde_json::Value = client::get("https://api.github.com/users/taylorotwell")
    .ensure_successful()
    .await?
    .json()?;

你也可以在检查响应后再调用 response.ensure_successful()?。

client::Error 将失败分为四类:

变体原因
Error::Connection没有收到响应(主机不可达、TLS 失败或超时)。
Error::Status使用 ensure_successful 或 retry 时收到非 2xx 状态。可调用 error.response() 查看响应。
Error::Decodejson() 无法将响应体反序列化为目标类型。
Error::Invalid无法构造请求(URL 或请求头无效)。

可对 client::Error 进行模式匹配以处理不同的失败类型:

rust
use laravel::http::client::{self, Error};

let request = client::get("https://api.github.com/users/taylorotwell")
    .ensure_successful();

match request.await {
    Ok(response) => {
        // ...
    }
    Err(Error::Connection(error)) if error.is_timeout() => {
        // ...
    }
    Err(Error::Status(response)) if response.status() == 404 => {
        // ...
    }
    Err(error) => return Err(error.into()),
}

在处理器中使用 ? 将错误转换为 laravel::Error 并返回时,Laravel 会报告该错误,返回 500,并在日志中记录 URL 和响应体开头的内容:

text
the HTTP request to https://api.example.com/users returned 404 Not Found: {"message":"Not found"}

并发请求 ​

需要从多个独立端点获取响应时,可以调用 .send() 获得每个请求的 future,通过 task::try_join! 并发发送:

rust
use laravel::http::client;
use laravel::task;

let (repository, release) = task::try_join!(
    client::get("https://api.github.com/repos/laravel/framework").send(),
    client::get("https://api.github.com/repos/laravel/framework/releases/latest").send(),
)?;

要在发送大量请求时限制并发数,可将它们包装为流并调用 .buffered(limit),它会保留输入顺序:

rust
use laravel::http::client;
use laravel::stream::{self, StreamExt};

let responses: Vec<_> = stream::iter(["laravel", "symfony", "rust-lang"])
    .map(|org| {
        client::get("https://api.github.com/orgs/{org}")
            .url_parameters([("org", org)])
            .send()
    })
    .buffered(5)
    .collect()
    .await;

流式响应 ​

下载大文件或使用流式 API(例如 AI 聊天补全)时,请调用 stream() 避免将整个响应体一次读入内存。收到响应头后,stream() 便会返回 StreamedResponse。

调用 chunks() 即可逐个字节块遍历响应体:

rust
use laravel::http::client;
use laravel::stream::TryStreamExt;

let mut chunks = client::get("https://example.com/exports/orders.csv")
    .ensure_successful()
    .stream()
    .await?
    .chunks();

while let Some(chunk) = chunks.try_next().await? {
    // 处理每个字节块……
}

也可以将 chunks() 直接传给文件存储,无需将下载内容缓存在内存中:

rust
use laravel::http::client;
use laravel::storage;

let response = client::get("https://example.com/exports/orders.csv")
    .ensure_successful()
    .stream()
    .await?;

storage::disk("local")?
    .write_stream("exports/orders.csv", response.chunks())
    .await?;

StreamedResponse 提供与 Response 相同的 status()、header() 及状态检查方法。响应体只能消费一次:用 chunks() 读取原始字节,用 events() 读取服务器发送事件,或用 into_response() 将剩余内容缓冲为常规 Response。

流式传输期间,请求超时限制分别作用于每次读取数据块的过程,因此持续传输数据的长连接不会因总时长过长而超时。

服务器发送事件 ​

很多 AI 和实时 API 通过服务器发送事件传输响应。调用 events() 可以逐个获取完整事件,并访问 data() 和 json()。

例如,这个处理器将 OpenAI 的流式补全结果通过 EventStream 响应转发给浏览器:

rust
use laravel::config::Section;
use laravel::http::client;
use laravel::http::sse::EventStream;
use laravel::stream::TryStreamExt;
use serde_json::json;

use crate::config::services::OpenAi;

pub async fn chat(openai: Section<OpenAi>) -> laravel::Result<EventStream> {
    let mut events = client::post("https://api.openai.com/v1/chat/completions")
        .token(&openai.key)
        .json(json!({
            "model": "gpt-6.2-sol",
            "stream": true,
            "messages": [{ "role": "user", "content": "Write a haiku about Rust." }],
        }))
        .ensure_successful()
        .stream()
        .await?
        .events();

    Ok(EventStream::channel(async move |sender| {
        while let Some(event) = events.try_next().await? {
            if event.data() == "[DONE]" {
                break;
            }

            let delta: serde_json::Value = event.json()?;

            if let Some(content) = delta["choices"][0]["delta"]["content"].as_str() {
                sender.send(content).await?;
            }
        }

        Ok(())
    }))
}

配置客户端 ​

laravel::http::client 中的所有顶层辅助函数(client::get、client::post、client::base_url 等)都会通过应用管理的同一个共享 Client 发出请求。共享 Client 使整个应用可以复用连接池中的 TCP 和 TLS 连接、默认超时时间以及请求钩子。

共享客户端使用以下默认值:

设置默认值
timeout30 秒
connect_timeout10 秒
user_agentLaravel-Rust/<version>

要为整个应用自定义这些默认值,请构建 Client,并在 src/app.rs 的 .with_services 中通过 app.instance 注册:

rust
use laravel::http::client::Client;
use laravel::prelude::*;

Application::configure()
    .with_services(|app| {
        app.instance(
            Client::new()
                .timeout(10.seconds())
                .connect_timeout(5.seconds())
                .user_agent("Acme/1.0")
                .before_sending(|request| request.header("x-tenant", "acme"))
                .after_response(|response| {
                    tracing::debug!(status = %response.status(), "API response");
                }),
        );
    })

通过 app.instance 注册客户端可以保证应用启动期间其他服务发出 HTTP 请求时,客户端已经可用。惰性的 singleton 则会推迟创建。

通过生命周期钩子,你可以检查或转换经过客户端的每个对外请求和响应。每次发出请求之前,before_sending 钩子会按注册顺序执行。after_response 钩子能观察到返回的每个响应,包括重试产生的响应和测试中的模拟响应。

如果某个 before_sending 钩子只适用于特定 API,请在修改请求前先检查 request.url():

rust
use laravel::http::client::Client;

let client = Client::new().before_sending(|request| {
    if request
        .url()
        .is_ok_and(|url| url.host_str() == Some("api.example.com"))
    {
        request.token("secret")
    } else {
        request
    }
});

传输选项 ​

如果需要直接配置底层 reqwest 传输,例如添加自定义 CA 证书、配置双向 TLS、HTTP 代理或修改重定向策略,请向 configure_transport 传入闭包。它接收 reqwest 的 ClientBuilder 并返回配置好的构建器。

请从 laravel::http::client::reqwest 导入 reqwest 类型,确保代码所用版本与 Laravel 自带的 reqwest 一致:

rust
use laravel::http::client::{Client, reqwest};

let client = Client::new().configure_transport(|transport| {
    transport.redirect(reqwest::redirect::Policy::none())
});

也可以只在单个请求上调用 configure_transport。这样会为该请求创建独立连接池,共享 Client 及应用中的其他请求仍可正常使用原有配置。

专用客户端 ​

某些第三方服务可能需要独立的 User-Agent、更严格的超时时间、自定义 TLS 证书或特殊重定向策略。对于只用于指定服务的设置,可以构建专用 Client,直接在它上面调用 get、post、base_url 等请求方法。

每个 Client 都维护自己的连接池,请避免在每次处理请求时新建客户端。可以将专用 Client 包装在服务中,在 src/app.rs 内注册一次,再按需注入:

rust
// src/services/reports.rs
use laravel::http::client::Client;
use laravel::prelude::*;

pub struct ReportsClient {
    http: Client,
}

impl ReportsClient {
    pub fn new() -> Self {
        Self {
            http: Client::new()
                .timeout(60.seconds())
                .user_agent("Acme Reports/1.0"),
        }
    }

    pub async fn monthly(&self) -> laravel::Result<String> {
        let response = self
            .http
            .get("https://reports.example.com/monthly")
            .ensure_successful()
            .await?;

        Ok(response.text().into_owned())
    }
}

在 src/app.rs 中注册服务,再在处理器中用 Inject 解析:

rust
// src/app.rs
use laravel::prelude::*;

use crate::services::reports::ReportsClient;

Application::configure()
    .with_services(|app| {
        app.instance(ReportsClient::new());
    })
rust
use laravel::prelude::*;

use crate::services::reports::ReportsClient;

pub async fn show(reports: Inject<ReportsClient>) -> laravel::Result<String> {
    reports.monthly().await
}

通过专用 Client 发出的请求仍会在测试中被 client::fake() 自动拦截。

日志 ​

HTTP 客户端会为每个对外请求在 laravel::http::client 目标上写入一条 debug 日志,记录方法、URL、状态和 duration_ms(或失败原因)。使用 LOG_LEVEL=info,laravel::http::client=debug 启用日志。记录 URL 和错误消息时会自动去掉凭据和查询字符串,以免泄露 API 密钥。

启用分布式追踪后,每次尝试都会生成独立 span 并发送自己的 W3C traceparent 头,因此重试请求的每一次尝试都能单独查看。

测试 ​

模拟响应 ​

在测试中调用 client::fake() 可以拦截对外请求并返回模拟响应,无需访问网络。默认每个请求都会收到内容为空的 200 响应:

rust
use laravel::http::client;
use laravel::testing::prelude::*;

#[laravel::test]
async fn shows_a_github_profile(app: Application) {
    let http = client::fake();

    app.get("/profile").await.assert_ok();

    http.assert_sent_count(1);
}

执行测试代码期间请保留返回的模拟句柄,丢弃后就会恢复真实的网络请求。模拟对象按测试应用隔离,因此并发测试互不干扰。

向 .with(..) 传入 URL 模式可以返回自定义响应。模式可匹配 URL 中的任意位置,支持 * 通配符,按注册顺序匹配。响应可以是状态码、字符串、JSON 值或 client::response() 构建器:

rust
use serde_json::json;

let http = client::fake()
    .with(
        "api.github.com/users/*",
        json!({ "login": "taylorotwell", "name": "Taylor Otwell" }),
    )
    .with(
        "api.stripe.com/*",
        client::response()
            .status(402)
            .json(json!({ "error": "card_declined" })),
    )
    .with("example.com/health", 503)
    .with("*", "Hello World");

使用 client::failed_connection() 可模拟网络故障,它会返回 Error::Connection:

rust
let http = client::fake().with("api.github.com/*", client::failed_connection());

模拟请求仍执行客户端钩子和重试逻辑,但会跳过重试间的等待。

说明

client::fake() 拦截通过 laravel::http::client 发送的请求。第三方 SDK 如果自行创建内部 HTTP 客户端,其请求会绕过此模拟。

响应序列 ​

用 client::sequence() 可以为同一个 URL 模式依次返回不同响应,适合测试重试行为:

rust
use laravel::http::client;
use serde_json::json;

let http = client::fake().with(
    "api.github.com/*",
    client::sequence()
        .push(client::failed_connection())
        .push(503)
        .push(json!({ "login": "taylorotwell" })),
);

序列耗尽后,继续请求会收到 Error::Invalid 错误,除非你通过 when_empty 配置了后备响应。和 push 一样,when_empty 接受任意模拟响应值:状态码、字符串、JSON 值、client::response() 构建器、client::failed_connection() 或回调闭包:

rust
let http = client::fake().with(
    "api.github.com/*",
    client::sequence().push("Hello World").when_empty(
        client::response()
            .status(404)
            .json(json!({ "error": "not_found" })),
    ),
);

模拟回调 ​

如果响应取决于收到的请求,请向 with 传入闭包。闭包会收到 &Request,可以返回任意模拟响应值(状态码、字符串、JSON 值或 client::response() 构建器):

rust
use laravel::http::client::{self, Request};

let http = client::fake().with("api.example.com/*", |request: &Request| {
    if request.has_header("authorization", "Bearer secret") {
        200
    } else {
        401
    }
});

在回调中可以使用与断言相同的 Request 方法检查对外请求的任意部分。

模拟流式响应 ​

代码调用 stream() 时,模拟响应体会逐行抵达。例如,下面的测试为聊天处理器模拟 OpenAI 服务器发送事件流:

rust
use laravel::http::client;
use laravel::testing::prelude::*;

#[laravel::test]
async fn chat_replies_stream(app: Application) {
    let http = client::fake().with(
        "api.openai.com/*",
        client::response()
            .header("content-type", "text/event-stream")
            .body(concat!(
                "data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\n",
                "data: {\"choices\":[{\"delta\":{\"content\":\"lo!\"}}]}\n\n",
                "data: [DONE]\n\n",
            )),
    );

    app.get("/chat")
        .await
        .assert_ok()
        .assert_see("data: Hel")
        .assert_see("data: lo!");
}

检查请求 ​

模拟对象启用期间会记录每个对外请求,包括重试请求。使用 assert_sent 验证至少有一条请求记录满足指定条件:

rust
use laravel::http::Method;

http.assert_sent(|request| {
    request.method() == Method::POST
        && request.url() == "https://example.com/users"
        && request.has_header("x-tenant", "acme")
        && request.data()["name"] == "Taylor"
});

http.assert_not_sent(|request| request.url().contains("/posts"));
http.assert_sent_count(5);
http.assert_nothing_sent();

在 assert_sent 判断函数和模拟回调中,Request 都能提供完整的对外请求:

方法说明
method()HTTP Method,如 GET、POST 等。
url()解析后的完整 URL,包括基础 URL 和查询字符串。
header(name)以 Option<&str> 获取请求头的文本值。
has_header(name, value)是否发送了指定名称和值的请求头。
headers()以 HeaderMap 获取全部对外请求头。
body()原始请求体字节(&[u8])。
data()以 serde_json::Value 获取解析后的 JSON、表单或 multipart 文本字段。
json::<T>()将 JSON 请求体反序列化为指定类型的结构体。
files()multipart 附件(&[SentFile])。
has_file(name, file_name)是否附加了指定字段名和文件名的 multipart 文件。

例如,可以用 has_file 检查 multipart 上传:

rust
http.assert_sent(|request| request.has_file("report", "q3.pdf"));

要编写自定义断言,sent() 返回所有已记录的请求,recorded() 返回 (Request, Response) 对:

rust
let [(request, response)] = http.recorded().try_into().unwrap();

assert_eq!(response.status(), 500);

未匹配的请求 ​

默认情况下,未匹配的请求会收到空的 200 响应。调用 prevent_stray_requests 可使所有意外请求都返回 Error::Invalid 错误:

rust
use serde_json::json;

let http = client::fake()
    .with("api.github.com/*", json!({ "login": "taylorotwell" }))
    .prevent_stray_requests();

要允许访问指定的真实主机(例如本地测试服务器),同时阻止其他未匹配请求,请使用 allow_stray_requests:

rust
use serde_json::json;

let http = client::fake()
    .with("api.github.com/*", json!({ "login": "taylorotwell" }))
    .allow_stray_requests(["http://127.0.0.1:5000/*"]);