rehyved/php-http-client

PHP curl http 库的简单易用的包装器

1.0.0-alpha 2018-06-23 14:24 UTC

This package is auto-updated.

Last update: 2024-09-07 05:13:44 UTC


README

PHP cURL 扩展之上实现的一个 HTTP 客户端,受构建器模式启发。

Build Status

此库使用与 Java 的 Apache HTTP 客户端 Fluent API 类似的构建器模式。目标是提供一个易于阅读和维护的方式来编写 PHP 网站和应用程序中的 HTTP 请求逻辑。

欢迎反馈。

安装

先决条件:

  • PHP 7.0 或更高版本
  • PHP cURL 模块 (ext-curl)
  • PHP DOM 模块 (ext-dom)

此库通过 Packagist 提供,并且可以使用 Composer 导入

composer require rehyved/php-http-client

使用

此库的目标是使在 PHP 中生成 HTTP 请求变得简单,同时保持代码的可读性和易于理解。此功能的主要起点是 HttpRequest 类HttpResponse 类

HttpRequest 类

以下示例展示了如何使用 HttpRequest 类进行不同的 HTTP 请求

覆盖默认配置

某些设置的默认配置可以全局配置,以避免在每次创建 HttpRequest 时提供这些值。

以下配置选项可以通过定义适当的常量来使用 define()

  • RPHC_DEFAULT_HEADERS - 一个关联数组,包含要包含在每个 HTTP 请求中的头部名称->头部值(默认:array()
  • RPHC_DEFAULT_TIMEOUT - 一个 int 值,表示用作 HTTP 请求超时时间的秒数(默认:30
  • RPHC_DEFAULT_VERIFY_SSL_CERTIFICATE - 一个布尔值,表示是否应在 HTTP 请求中强制执行 SSL 证书的有效性(默认:true

请求类型

GET 请求
$response = HttpRequest::create("https://httpbin.org")  // Base url
    ->get("get");                                       // Path

https://httpbin.org 是一个很好的服务,可以用来测试 HTTP 请求,它提供了多种方式来尝试不同类型的请求,并可以配置响应

PUT 请求
$response = HttpRequest::create("https://httpbin.org")  // Base url
    ->contentType("application/json")                   // Content-Type header
->put("put", array("key" => "value");                   // Path & body
POST 请求
$response = HttpRequest::create("https://httpbin.org")  // Base url
    ->contentType("application/json")                   // Content-Type header
->post("post", array("key" => "value");                 // Path & body
DELETE 请求
$response = HttpRequest::create("https://httpbin.org")  // Base url
    ->contentType("application/json")                   // Content-Type header
->delete("delete", array("key" => "value");               // Path & body

添加查询参数

$response = HttpRequest::create("https://httpbin.org")  // Base url
    ->parameter("search", "Search query")               // Add a single query parameter
    ->parameters(array("key" => "value"))               // Add an array of query parameters
    ->get("get");                                       // Path

添加头部信息

$response = HttpRequest::create("https://httpbin.org")  // Base url
    ->header("Accept", "application/json")              // Add a single header
    ->headers(array("key" => "value"))                  // Add an array of headers
    ->get("get");                                       // Path

添加 cookies

$response = HttpRequest::create("https://httpbin.org")  // Base url
    ->cookie("search", "Search query")                  // Add a single cookie
    ->cookies(array("key" => "value"))                  // Add an array of cookies
    ->cookies()                                         // Adds all cookies from $_COOKIE to the request
    ->get("get");                                       // Path

基本认证

$response = HttpRequest::create("https://httpbin.org")  // Base url
    ->basicAuthentication("username", "password")       // Adds basic authentication to the request
    ->get("get");                                       // Path

授权头部

$response = HttpRequest::create("https://httpbin.org")  // Base url
    ->authorization("Bearer", "<JWT-token>")            // Convenience method to add an Authorization header
    ->get("get");                                       // Path

更改请求超时时间

$response = HttpRequest::create("https://httpbin.org")  // Base url
    ->timeout(20)                                       // Changes the timeout for the request to 20 seconds
    ->get("get");                                       // Path

禁用 SSL 证书验证

注意:此功能不建议在生产系统中使用,但在测试环境中作为便利选项

$response = HttpRequest::create("https://httpbin.org")  // Base url
    ->verifySslCertificate(false)                       // Disables the verification of SSL certificates
    ->get("get");                                       // Path

HttpResponse 类

$response 变量将保存 HttpResponse 实例。此类对象持有 HttpRequest 的结果内容,并提供了有用的方法来提取更多信息。

状态处理

$isError = $response->isError()){ // checks the HTTP status to see if it is an error see the HttpStatus class
$statusCode = $response->getHttpStatus(); 

头部处理

$contentType = $response->getContentType();
$header = $response->getHeader("Content-Type");
$headers = $response->getHeaders(); // an associative array of header name -> header value

cookies 处理

$cookie = $response->getCookie("chocolatechip"); // returns a HttpCookie object
$cookie = $response->getCookies(); // a list of HttpCookie objects
$response->importCookies(); // Adds all cookies to the current session by using setcookie (https://php.ac.cn/manual/en/function.setcookie.php)

响应体处理

$contentLength = $response->getContentLength();
$content = $response->getContent(); // Will deserialize JSON or XML content if the matching Content-Type was received 
$contentRaw = $response->getContentRaw() // Does not try to deserialize and returns the raw response body

HttpStatus 类

此类提供常量以获取与 HTTP 状态匹配的状态代码,以及方便的方法来获取原因短语和检查状态代码的类型。

常量

该类提供了HTTP状态的常量,例如

HttpStatus::OK
HttpStatus::CLIENT_ERROR
HttpStatus::SERVER_ERROR

etc...

方法

HttpStatus::isInformational(int $statusCode)
HttpStatus::isSuccessful(int $statusCode)
HttpStatus::isRedirection(int $statusCode)
HttpStatus::isClientError(int $statusCode)
HttpStatus::isServerError(int $statusCode)
HttpStatus::isError(int $statusCode)
HttpStatus::getReasonPhrase(int $statusCode)