osti/http-client-php

PHP 的 HTTP 客户端库

1.0.1 2023-08-28 20:09 UTC

This package is auto-updated.

Last update: 2024-09-28 22:20:44 UTC


README

支持 Guzzle-HTTP 的 PHP Http 库

HttpClient 类是一个 PHP 类,使用 GuzzleHttp 库简化 HTTP 请求。此类提供了一个简单的接口来执行 HTTP GET、POST、PUT 和 DELETE 请求,同时允许自定义请求参数、头和 cookie 管理。

安装

要使用此类,您需要安装 GuzzleHttp 库。您可以使用 Composer 安装它

composer require osti/http-client-php

用法

以下是如何使用 HttpClient 类执行 HTTP GET 请求的示例

use HttpClient;

// Create an instance of HttpClient
$http = new HttpClient();

// Make an HTTP GET request
$response = $http->makeRequest('GET', 'https://www.example.com');

// Handle the response
if ($response !== false) {
    // The request was successful
    echo $response; // Response content
} else {
    // An error occurred during the request
    echo "Error during the request.";
}

主要方法

构造函数

HttpClient 类的构造函数接受两个可选参数:$cookies$verify。将 $cookies 设置为 true 将启用 cookie 的使用,并创建一个临时文件来存储它们。将 $verify 设置为 true 将启用 SSL 验证。以下是一个示例用法

$http = new HttpClient($cookies = true, $verify = true);

addHeaders(array $headers)

向请求添加 HTTP 头。以下是一个示例

$http->addHeaders([
    'User-Agent' => 'My User Agent',
    'Authorization' => 'Bearer Token123'
]);

setBody($params, $needEncode = true)

设置 HTTP 请求 的正文。您可以指定请求中要发送的参数。如果 $needEncode 设置为 true,则参数将被编码为 JSON。以下是一个示例

$http->setBody([
    'query' => ['key' => 'value'],
    'json' => ['data' => 'content']
]);

其他方法

HttpClient 类还提供其他有用的方法,例如 hideHeaders()setTimeout()setOption()deleteOption() 等。