定制 rehyved/php-http-client 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

rehyved/php-http-client

Composer 安装命令:

composer require rehyved/php-http-client

包简介

An easy to use wrapper for the curl http library in PHP

README 文档

README

A HTTP Client implementation on top of the PHP cURL extension for PHP inspired by the builder pattern.

Build Status

This library uses a builder pattern similar to the Apache HTTP client Fluent API for Java. The goal is to provide a readable and maintainable way of writing HTTP request logic inside your PHP websites and applications.

Feedback is always welcome.

Installation

Prerequisites:

  • PHP 7.0 or higher
  • PHP cURL module (ext-curl)
  • PHP DOM module (ext-dom)

This library is available through Packagist and can be imported using Composer:

composer require rehyved/php-http-client

Usage

The goal with this library is to make it easy to produce HTTP requests in PHP whilst keeping the code readable and understandable. The main starting point for this is the HttpRequest class and the HttpResponse class.

HttpRequest class

The following examples show different usages of the HttpRequest class to perform HTTP requests:

Overriding default configuration

Default configuration for some settings can be configured globally to prevent having to provide these values on each creation of an HttpRequest.

The following configuration options are available by defining the appropriate constants with define():

  • RPHC_DEFAULT_HEADERS - An associative array of header name-> header value to be included with each HTTP request (default: array())
  • RPHC_DEFAULT_TIMEOUT - An int value indicating the number of seconds to use as a timeout for HTTP requests (default: 30)
  • RPHC_DEFAULT_VERIFY_SSL_CERTIFICATE - a boolean value indicating if the validity of SSL certificates should be enforced in HTTP requests (default: true)

Request types

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

https://httpbin.org is a nice service to test HTTP requests against, it provides several ways to try different kinds of requests with a configurable response

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

Adding query parameters

$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

Adding Headers

$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

Adding 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

Basic Authentication

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

Authorization header

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

Changing request timeout

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

Disabling SSL certificate verification

NOTE: This feature is not recommended in a production system but is meant as a convenience option in test environments

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

HttpResponse class

The $response variable will hold an instance of HttpResponse. This type of object holds the resulting content of the HttpRequest and provides useful methods to extract further information.

Status handling

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

Header handling

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

Cookie handling

$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 (http://php.net/manual/en/function.setcookie.php)

Response body handling

$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 class

This class provides constants to retrieve the matching status code for an HTTP status as well as convenience methods to get the reason phrase and check the type of a status code.

Constants

The class provides constants for the HTTP statuses, for example:

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

etc...

Methods

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)

rehyved/php-http-client 适用场景与选型建议

rehyved/php-http-client 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2017 年 05 月 01 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「http」 「client」 「http-client」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 rehyved/php-http-client 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 rehyved/php-http-client 我们能提供哪些服务?
定制开发 / 二次开发

基于 rehyved/php-http-client 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 5
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-05-01