shewa12 / wp-http-client
WordPress wp_remote_request API 的 HTTP 请求包装类。
v1.0.0
2023-08-06 15:59 UTC
Requires
- php: >=7.4
This package is auto-updated.
Last update: 2024-09-08 20:32:01 UTC
README
wp-http-client
是一个用于通过 WordPress API 进行 HTTP 请求的 PHP Composer 包。它提供了一种轻松进行 GET、POST、PUT 和 DELETE 请求的方法。这个类对于正在开发 WordPress 插件或主题并与外部 API 或远程服务交互的开发者特别有用。
安装
composer require shewa12/wp-http-client
实例化 HTTPClient 类
要使用 wp-http-client
,请按如下方式创建其实例
use Shewa\WP_HTTP_Client\HTTPClient; // Instantiate the HTTPClient class $http_client = new HTTPClient();
用法
request()
方法负责执行 HTTP 请求。此方法接受四个参数。它们是:
- $request,必需。需要进行的请求。支持的值:get、post、put、patch、delete。
- $url,必需。请求的位置
- $data,如果请求不是 get 或 delete 则必需
- $args,可选,用于覆盖默认值
GET 请求示例
$url = 'https://api.example.com/data'; $response = $http_client->request( 'get', $url ); if ( ! is_wp_error( $response ) ) { // Process the response data print_r( $response ); } else { // Handle the error echo 'Error: ' . $response->get_error_message(); }
POST 请求示例
$url = 'https://api.example.com/data'; $data = ['name' => 'John']; $response = $http_client->request( 'post', $url, $data ); if ( ! is_wp_error( $response ) ) { // Process the response data print_r( $response ); } else { // Handle the error echo 'Error: ' . $response->get_error_message(); }
响应
响应将是 WP_Error 或数组。
成功的响应将返回如下所示的数组
$response = array( 'headers' => [], 'code' => 200, 'message' => 'OK', 'body' => [], );
方法
- REQUEST
- GET
- POST
- PUT
- PATCH
- DELETE
支持的 HTTP 参数 & 默认值
$defaults = array( 'method' => 'GET', 'timeout' => 5, 'redirection' => 5, 'httpversion' => 1.0, 'user-agent' => 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' )', 'reject_unsafe_urls' => false, 'blocking' => true, 'headers' => array(), 'cookies' => array(), 'body' => null, 'compress' => false, 'decompress' => true, 'sslverify' => true, 'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt', 'stream' => false, 'filename' => null, 'limit_response_size' => null, );