Skip to main content

HttpClient

Struct HttpClient 

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

HTTP 客户端

提供 HTTP 请求构建和发送能力。

内部持有 Arc<reqwest::Client>,clone() 时复用同一连接池(即 Arc::clone), 不会创建新的底层连接池。

§示例

ⓘ
use yang_base::http::HttpClient;
use yang_base::tools::ToolsBuilder;

// 启动期:把客户端注册进应用资源并冻结
let tools = ToolsBuilder::new().http(HttpClient::new(30)?).build()?;

// 运行期:从 Tools 获取客户端发起请求(Action 内为 ctx.http()?)
let response = tools.http()?
    .get("https://api.example.com/users")
    .send()
    .await?;

Implementations§

Source§

impl HttpClient

Source

pub fn with_config(cfg: HttpClientConfig) -> Result<Self, BaseError>

使用结构化配置创建 HTTP 客户端

§参数
  • cfg: HTTP 客户端配置
§返回
  • Ok(HttpClient): 客户端实例
  • Err(BaseError::HttpClientCreateFailed): 创建失败(如代理 URL 无效)
§示例
ⓘ
use yang_base::http::{HttpClient, HttpClientConfig};

let config = HttpClientConfig {
    timeout_secs: 60,
    pool_max_idle_per_host: 20,
    ..Default::default()
};
let client = HttpClient::with_config(config)?;
Source

pub fn new(timeout_secs: u64) -> Result<Self, BaseError>

创建新的 HTTP 客户端

委托给 with_config,使用默认配置并仅覆盖超时时间。

§参数
  • timeout_secs: 默认超时时间(秒)
§返回
  • Ok(HttpClient): 客户端实例
  • Err(BaseError): 创建失败
§示例
ⓘ
let client = HttpClient::new(30)?;
Source

pub fn set_default_token(&self, token: String)

设置默认 Token

§参数
  • token: Token 字符串
§示例
ⓘ
let mut client = HttpClient::new(30)?;
client.set_default_token("your_token".to_string());
Source

pub fn request(&self, method: Method, url: &str) -> RequestBuilder

创建请求构建器

注意:self.client.clone() 是 Arc::clone,复用同一底层连接池, 不会创建新的 TCP 连接池,多个请求共享连接。

§参数
  • method: HTTP 方法
  • url: 请求 URL
§返回
  • RequestBuilder: 请求构建器
§示例
ⓘ
use reqwest::Method;

let response = client
    .request(Method::GET, "https://api.example.com/users")
    .send()
    .await?;
Source

pub fn get(&self, url: &str) -> RequestBuilder

GET 请求

§参数
  • url: 请求 URL
§返回
  • RequestBuilder: 请求构建器
§示例
ⓘ
let response = client
    .get("https://api.example.com/users")
    .send()
    .await?;
Source

pub fn post(&self, url: &str) -> RequestBuilder

POST 请求

§参数
  • url: 请求 URL
§返回
  • RequestBuilder: 请求构建器
§示例
ⓘ
let response = client
    .post("https://api.example.com/users")
    .json(&user)?
    .send()
    .await?;
Source

pub fn put(&self, url: &str) -> RequestBuilder

PUT 请求

§参数
  • url: 请求 URL
§返回
  • RequestBuilder: 请求构建器
§示例
ⓘ
let response = client
    .put("https://api.example.com/users/1")
    .json(&user)?
    .send()
    .await?;
Source

pub fn delete(&self, url: &str) -> RequestBuilder

DELETE 请求

§参数
  • url: 请求 URL
§返回
  • RequestBuilder: 请求构建器
§示例
ⓘ
let response = client
    .delete("https://api.example.com/users/1")
    .send()
    .await?;
Source

pub fn patch(&self, url: &str) -> RequestBuilder

PATCH 请求

§参数
  • url: 请求 URL
§返回
  • RequestBuilder: 请求构建器
§示例
ⓘ
let response = client
    .patch("https://api.example.com/users/1")
    .json(&updates)?
    .send()
    .await?;

Trait Implementations§

Source§

impl Clone for HttpClient

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for HttpClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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