定制 originphp/http-client 二次开发

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

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

originphp/http-client

Composer 安装命令:

composer require originphp/http-client

包简介

OriginPHP HTTP Client

README 文档

README

license build coverage

The HTTP client is a simple yet very powerful utility for making HTTP requests.

Installation

To install this package

$ composer require originphp/http-client

Sending Requests

Get Request

To send a GET request

use Origin\HttpClient\Http;
$http = new Http();
$response = $http->get('https://api.example.com/posts');

// To use query parameters. https://api.example.com/posts?api_token=1234-1234-1234-1234
$response = $http->get('https://api.example.com/posts',[
    'query' => ['api_token' => '1234-1234-1234-1234']
]);

// An example with more options
$response = $http->get('https://api.example.com/posts',[
    'headers' => ['Accept' => 'application/json'],
    'cookies' => ['name' => 'value'],
    'userAgent' => 'MyApp',
    'referer' => 'https://www.somewebsite.com/search'
]);

The full list of options are detailed below.

Head Request

To make HEAD request, where the body of the request is not fetched.

use Origin\HttpClient\Http;
$http = new Http();
$response = $http->head('https://api.example.com/posts');

// To use query parameters. https://api.example.com/posts?api_token=1234-1234-1234-1234
$response = $http->head('https://api.example.com/posts',[
    'query' => ['api_token' => '1234-1234-1234-1234']
]);

// An example with more options
$response = $http->head('https://api.example.com/posts',[
    'headers' => ['Accept' => 'application/json'],
    'cookies' => ['name' => 'value'],
    'userAgent' => 'MyApp',
    'referer' => 'https://www.somewebsite.com/search'
]);

Post Request

To send a POST request. In REST terms post requests are used to create a record.

use Origin\HttpClient\Http;
$http = new Http();

// to send a post request with empty data
$response = $http->post('https://api.example.com/posts');

// to send a post request with data
$response = $http->post('https://api.example.com/posts',[
    'data' => [
        'title' => 'Article Title',
        'body' => 'Article body'
    ]
]);

// example with other options
$response = $http->post('https://api.example.com/posts',[
    'data' => [
        'title' => 'Article Title',
        'body' => 'Article body'
    ],
    'headers' => ['Accept' => 'application/json'],
    'cookies' => ['name' => 'value'],
    'userAgent' => 'MyApp',
    'referer' => 'https://www.somewebsite.com/search'
]);

To upload files using a post request.

use Origin\HttpClient\Http;
$http = new Http();
$response = $http->post('https://api.example.com/posts',[
    'data' => [
        'contacts' => Http::file('/docs/contacts.csv')
    ]
]);

// Shortcut for Http::file
$response = $http->post('https://api.example.com/posts',[
    'data' => [
        'contacts' => '@/docs/contacts.csv'
    ]
]);

Put Request

To send a PUT request. In REST terms put requests are used to modify a record with complete data (overwriting).

use Origin\HttpClient\Http;
$http = new Http();
$response = $http->put('https://api.example.com/posts/1',[
    'data' => [
        'title' => 'Changed Article Title',
        'body' => 'Article body'
    ],
]);

Patch Request

To send a PATCH request. In REST terms patch requests are used to modify an existing record with partial data.

use Origin\HttpClient\Http;
$http = new Http();
$response = $http->patch('https://api.example.com/posts/1',[
     'data' => [
        'title' => 'Another Article Title',
    ],
]);

Delete Request

To send a DELETE request.

use Origin\HttpClient\Http;
$http = new Http();
$response = $http->delete('https://api.example.com/posts/1');

// Example passing some options
$response = $http->delete('https://api.example.com/posts/1',[
    'userAgent' => 'OriginPHP'
]);

HTTP Request Options

The available options when making requests are

  • query: appends vars to the query. e.g ['api_token' => '1234-1234-1234-1234']
  • userAgent: the name of the user agent to use e.g. 'originPHP'
  • referer: default null. The url of the referer e.g. 'https://www.example.com/search'
  • redirect: default true. set to false to not follow redirects
  • timeout: default timeout is 30 seconds
  • cookieJar: default true. Persists cookies for instance. Set to false to not perist cookies. Pass a string with filename and path to save to and read cookies from. e.g. '/var/www/data/cookies.data'
  • type: request and accept content type (json xml) e.g. 'json'
  • auth: authtentication details. An array with username, password, and type (basic|digest|nltm)
  • proxy: proxy server details. An array with proxy, username, password.
  • curl: an array of curl options either string or constant e.g [CURLOPT_SSL_VERIFYHOST=>0, 'ssl_verifypeer'=>0]
  • headers: an array of headers to set. e.g ['Accept' => 'application/json']
  • cookies: an array of cookies to set. e.g. ['name' => 'value']
  • fields: This option is for post/put/patch requests. Its an array of fields to be posted e.g. ['title' => 'Article #1','description' => 'An article']

Configuring the Http Client

You configure Http client so that you don't have to keep on passing options which makes code longer and more prone to errors.

This is particularly useful when working with multiple requests in an instance. Any options passed when creating the instance will be used as default for each request, unless you specify something else during the request.

use Origin\HttpClient\Http;
$http = new Http([
    'base' => 'https://www.example.com/api'
]);
$response = $http->get('/posts');

Other options:

  • userAgent
  • timeout
  • cookieJar
  • type
  • auth
  • proxy
  • referer
  • headers
  • cookies
  • verbose

Exceptions (version ^2.0)

In 2.0 various exceptions have been added, and a HTTP protocol error handler has also been added. All exceptions from the http client extend the HttpClientException class.

Request Exceptions

In the event of connection issues (DNS, timeout etc), a ConnectionException will be thrown, and a TooManyRedirectsException will be thrown on redirect loops, and any other cURL error will trigger a generic RequestException.

HTTP Protocol Exceptions

By default any 4xx and 5xx errors will throw either ClientErrorException or ServerErrorException which both extend the HttpException class.

This behavior can be disabled by setting httpErrors to false when creating the Http instance.

$http = new Http([
    'httpErrors' => false
]);

To catch HTTP protocol errors

try {
    (new Http())->get('http://wwww.google.com');
} catch (HttpException $exception) {
    // do something
}

Working with Responses

When you make a HTTP request, a Response object is returned.

use Origin\HttpClient\Http;
$http = new Http();
$response = $http->head('https://api.example.com/posts');

// working with the response body
$data = $response->body();
$data = $response->json(); // decodes a JSON response into an array
$data = $response->xml(); // converts XML response into an array

// Response stuff
$headers = $response->headers(); // headers
$cookies = $response->cookies(); // cookies from the *response*
$code = $response->statusCode();

// Assertions
$bool = $response->ok(); // has status code of 200
$bool = $response->success(); // has any 20x status code
$bool = $response->redirect(); // has a redirect status code 30x

Cookies

By default cookies are persisted across all requests for the instance.

To change this behavior use the cookieJar option.

use Origin\HttpClient\Http;

// Persist cookies for this session only (stores in array)
$http = new Http([
    'cookieJar' => true
]);

// Don't use cookies
$http = new Http([
    'cookieJar' => false;
]);

// Persist cookies to file
$http = new Http([
    'cookieJar' => '/var/www/data/cookies.data';
]);

cURL Options

Occasionally, you might need to set additional cURL options, one example of this, is when there is an issue with SSL certificates. You can set cURL options with the CURLOPT constant or string version of it.

use Origin\HttpClient\Http;
$http = new Http();
$response = $http->get('https://api.example.com/posts',[
    'curl' => [
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0
        ]
]);

$http = new Http();
$response = $http->get('https://api.example.com/posts',[
    'curl' => [
        'ssl_verifyhost' => 0,
        'ssl_verifypeer' => 0
        ]
]);

To set these as default for settings for all the requests, configure it when creating the Http instance.

use Origin\HttpClient\Http;
$http = new Http([
    'curl' => [
        'ssl_verifyhost' => 0,
        'ssl_verifypeer' => 0
        ]
    ]);

Downloading a file

To download a file

$path =  '/var/www/file.tar.gz';
$fp = fopen($path, 'w');

$http = new Http();
$response = $http->get('https://example.com/file.tar.gz',[
    'curl' => [
        CURLOPT_HEADER => false,
        CURLOPT_FILE => $fp
    ]
]);

fclose($fp);

Setting Cookies

To set a cookie

use Origin\HttpClient\Http;
$response = $http->get('https://api.example.com/posts',[
    'cookies' => [
        'name' => 'value'
        ]
    ]);

User Authentication

The available authentication types are basic, digest, nltm or any.

use Origin\HttpClient\Http;
$response = $http->get('https://api.example.com/posts',[
    'auth' => [
        'username' => 'foo',
        'password' => 'secret',
        'type' => 'digest
        ]
    ]);

Using a Proxy

To send a HTTP request using a proxy server.

use Origin\HttpClient\Http;

// without authentication
$response = $http->get('https://api.example.com/posts',[
    'proxy' => [
        'proxy' => 'https://www.proxy.com:8080'
        ]
    ]);

// with authentication
$response = $http->get('https://api.example.com/posts',[
    'proxy' => [
        'proxy' => 'https://www.proxy.com:8080',
        'username' => 'foo',
        'password' => 'secret'
        ]
    ]);

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

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

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-10-12