Skip to main content

RequestBuilder

Struct RequestBuilder 

Source
pub struct RequestBuilder { /* private fields */ }
Expand description

HTTP 请求构建器

提供链式调用接口构建 HTTP 请求。

§Header 错误处理

header、headers 等方法在解析失败时不会立即返回错误,而是将错误信息 累积到内部 header_errors 列表中。调用 send() 时,若存在累积的 header 错误,则返回 BaseError::ParamInvalid("header", ...) 而不发送请求。

§示例

ⓘ
// tools 为启动期经 ToolsBuilder::http(...) 冻结的应用资源;Action 内则用 ctx.http()?
let response = tools.http()?
    .get("https://api.example.com/users")
    .header("X-Custom-Header", "value")
    .query("page", "1")
    .bearer_token("your_token")
    .timeout(60)
    .send()
    .await?;

Implementations§

Source§

impl RequestBuilder

Source

pub fn header(self, name: &str, value: &str) -> Self

设置请求头

若 header 名称或值解析失败,错误信息将被累积到内部错误列表, 不会立即返回错误。调用 send() 时若存在累积错误则返回 BaseError::ParamInvalid。

§参数
  • name: 请求头名称
  • value: 请求头值
§示例
ⓘ
let response = client
    .get("https://api.example.com/users")
    .header("X-Custom-Header", "value")
    .send()
    .await?;
Source

pub fn headers(self, headers: Vec<(&str, &str)>) -> Self

批量设置请求头

若任意 header 名称或值解析失败,错误信息将被累积到内部错误列表, 不会立即返回错误。调用 send() 时若存在累积错误则返回 BaseError::ParamInvalid。

§参数
  • headers: 请求头列表
§示例
ⓘ
let response = client
    .get("https://api.example.com/users")
    .headers(vec![
        ("X-Custom-Header-1", "value1"),
        ("X-Custom-Header-2", "value2"),
    ])
    .send()
    .await?;
Source

pub fn content_type(self, content_type: &str) -> Self

设置 Content-Type

§参数
  • content_type: Content-Type 值
§示例
ⓘ
let response = client
    .post("https://api.example.com/users")
    .content_type("application/json")
    .send()
    .await?;
Source

pub fn bearer_token(self, token: &str) -> Self

设置 Bearer Token

§参数
  • token: Token 字符串
§示例
ⓘ
let response = client
    .get("https://api.example.com/users")
    .bearer_token("your_token")
    .send()
    .await?;
Source

pub fn user_agent(self, user_agent: &str) -> Self

设置 User-Agent

§参数
  • user_agent: User-Agent 值
§示例
ⓘ
let response = client
    .get("https://api.example.com/users")
    .user_agent("MyApp/1.0")
    .send()
    .await?;
Source

pub fn query(self, key: &str, value: &str) -> Self

添加查询参数

§参数
  • key: 参数名
  • value: 参数值
§示例
ⓘ
let response = client
    .get("https://api.example.com/users")
    .query("page", "1")
    .query("limit", "10")
    .send()
    .await?;
Source

pub fn queries(self, params: Vec<(&str, &str)>) -> Self

批量添加查询参数

§参数
  • params: 查询参数列表
§示例
ⓘ
let response = client
    .get("https://api.example.com/users")
    .queries(vec![("page", "1"), ("limit", "10")])
    .send()
    .await?;
Source

pub fn json<T: Serialize>(self, json: &T) -> Result<Self, BaseError>

设置 JSON 请求体

§参数
  • json: 可序列化为 JSON 的数据
§返回
  • Ok(Self): 设置成功
  • Err(BaseError): 序列化失败
§示例
ⓘ
#[derive(Serialize)]
struct User {
    name: String,
    email: String,
}

let user = User {
    name: "Alice".to_string(),
    email: "alice@example.com".to_string(),
};

let response = client
    .post("https://api.example.com/users")
    .json(&user)?
    .send()
    .await?;
Source

pub fn form(self, form: Vec<(&str, &str)>) -> Self

设置表单请求体

使用 serde_urlencoded 对表单数据进行 URL 编码,正确处理特殊字符、 空格、UTF-8 字符等,并自动设置 Content-Type: application/x-www-form-urlencoded。

§参数
  • form: 表单数据(键值对列表)
§示例
ⓘ
let response = client
    .post("https://api.example.com/login")
    .form(vec![("username", "alice"), ("password", "secret")])
    .send()
    .await?;
Source

pub fn body(self, body: Vec<u8>) -> Self

设置原始字节请求体

§参数
  • body: 字节数据
§示例
ⓘ
let response = client
    .post("https://api.example.com/upload")
    .body(vec![0x00, 0x01, 0x02])
    .send()
    .await?;
Source

pub fn text(self, text: &str) -> Self

设置文本请求体

§参数
  • text: 文本数据
§示例
ⓘ
let response = client
    .post("https://api.example.com/notes")
    .text("Hello, World!")
    .send()
    .await?;
Source

pub fn timeout(self, timeout_secs: u64) -> Self

设置超时时间

§参数
  • timeout_secs: 超时时间(秒)
§示例
ⓘ
let response = client
    .get("https://api.example.com/users")
    .timeout(60)
    .send()
    .await?;
Source

pub fn max_response_bytes(self, bytes: usize) -> Self

设置出站响应体最大允许字节数。

与 HttpClientConfig::max_response_bytes 语义一致:读取响应体时超限 返回 BaseError::HttpResponseTooLarge。设为 0 会在 send() 前被拒绝。

§参数
  • bytes: 响应体最大允许字节数(必须大于 0)
§示例
ⓘ
let response = client
    .get("https://api.example.com/users")
    .max_response_bytes(1024 * 1024)
    .send()
    .await?;
Source

pub fn retry(self, config: RetryConfig) -> Self

设置请求级重试策略(L-4)。

默认不重试。启用后,对连接错误与命中 retry_on 的状态码按指数退避重试。

非幂等方法(POST/PATCH)默认不参与重试,需 RetryConfig::retry_non_idempotent 置为 true 才显式承担重复写风险。

§参数
  • config: 重试策略
§示例
ⓘ
use yang_base::http::RetryConfig;

let response = client
    .get("https://api.example.com/users")
    .retry(RetryConfig::default())
    .send()
    .await?;
Source

pub async fn send(self) -> Result<Response, BaseError>

发送请求

在发送前检查累积的 header 错误。若存在任何 header 解析错误, 则返回 BaseError::ParamInvalid("header", ...) 而不发送请求。

§返回
  • Ok(Response): 响应对象
  • Err(BaseError::ParamInvalid): 存在非法 header
  • Err(BaseError::HttpRequestFailed): 请求发送失败
§示例
ⓘ
let response = client
    .get("https://api.example.com/users")
    .send()
    .await?;

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more