aura/http

Aura HTTP 包提供了从服务器到客户端构建和发送 HTTP 响应的对象。

安装次数: 36,886

依赖项: 1

建议者: 0

安全: 0

星级: 72

观察者: 13

分支: 21

公开问题: 0

类型: aura-package

1.0.3 2014-05-31 00:00 UTC

This package is auto-updated.

Last update: 2024-09-11 03:57:54 UTC


README

Build Status

Aura HTTP 包提供了构建和发送 HTTP 请求和响应的对象,包括 multipart/form-data 请求,当使用 curl 适配器时,可流式传输文件资源。

此包符合 PSR-0PSR-1PSR-2。如果您注意到符合性疏忽,请通过拉取请求发送补丁。

入门指南

实例化

开始使用最简单的方法是使用 scripts/instance.php 脚本实例化一个 HTTP Manager 对象。

<?php
$http = include '/path/to/Aura.Http/scripts/instance.php';

然后,您可以创建新的 RequestResponse 对象,并通过 Manager 发送它们。

<?php
// send a response
$response = $http->newResponse();
$response->headers->set('Content-Type', 'text/plain');
$response->setContent('Hello World!');
$http->send($response);

// make a request and get a response stack
$request = $http->newRequest();
$request->setUrl('http://example.com');
$stack = $http->send($request);
echo $stack[0]->content;

HTTP 响应

实例化

使用 Manager 创建新的 HTTP 响应。

<?php
$response = $http->newResponse();

设置和获取内容

要设置 Response 的内容,使用 setContent()

<?php
$html = '<html>'
      . '<head><title>Test</title></head>'
      . '<body>Hello World!</body>'
      . '</html>';
$response->setContent($html);

内容可以是文件资源,而不是字符串;当响应发送时,文件将通过 fread() 流式传输。

要获取内容,使用 getContent() 或访问 $content 属性。

设置和获取头部信息

要设置头部信息,访问 $headers 属性,并使用其 set() 方法。

<?php
$response->headers->set('Header-Label', 'header value');

您也可以通过传递一个数组(其中键是头部标签,值是一个或多个头部值)来一次设置所有头部信息。

<?php
$response->headers->setAll([
    'Header-One' => 'header one value',
    'Header-Two' => [
        'header two value A',
        'header two value B',
        'header two value C',
    ],
]);

注意:头部标签将被清洗和规范化,因此如果您输入标签 header_foo,它将被转换为 Header-Foo

要获取头部信息,使用 getHeaders() 或访问 $headers 属性并使用 get() 方法。

<?php
// set a header
$response->headers->set('Content-Type', 'text/plain');

// get a header
$header = $response->headers->get('Content-Type');

// $header->label is 'Content-Type'
// $header->value is 'text/plain'

设置和获取 Cookie

要设置 Cookie,访问 $cookies 属性。传递 Cookie 名称和包含 Cookie 信息(包括其值)的数组。

<?php
$response->cookies->set('cookie_name', [
    'value'    => 'cookie value', // cookie value
    'expire'   => time() + 3600,  // expiration time in unix epoch seconds
    'path'     => '/path',        // server path for the cookie
    'domain'   => 'example.com',  // domain for the cookie
    'secure'   => false,          // send by ssl only?
    'httponly' => true,           // send by http/https only?
]);

信息数组键模拟 setcookies() 参数名称。您只需要提供所需的数组部分;其余部分将使用 null 默认值为您填写。

您也可以通过传递一个键值对数组(其中键是 Cookie 名称,值是包含 Cookie 信息的数组)一次设置所有 Cookie。

<?php
$response->cookies->setAll([
    'cookie_foo' => [
        'value' => 'value for cookie foo',
    ],
    'cookie_bar' => [
        'value' => 'value for cookie bar',
    ],
]);

要获取 Cookie,使用 getCookies() 或访问 $cookies 属性并使用 get() 方法。

<?php
$cookie = $response->cookies->get('cookie_foo');

设置和获取状态

要设置 HTTP 响应状态,使用 setStatusCode()setStatusText()setStatusCode() 方法将自动为已知代码设置文本。

<?php
// automatically sets the status text to 'Not Modified'
$response->setStatusCode(304);

// change the status text to something else
$response->setStatusText('Same As It Ever Was');

注意:默认情况下,新的 Response'200 OK' 状态开始。

要获取响应状态,使用 getStatusCode()getStatusText()

发送响应

一旦设置了内容、头部信息、Cookie 和状态,您可以使用 HTTP Manager 对象发送响应。

<?php
$http->send($response);

这将使用 header() 发送所有头部信息,并使用 setcookie() 发送所有 Cookie。

如果内容是字符串,则会被 echo 输出;如果内容是文件资源,则使用 fread() 流式输出。

注意:您只能发送一次 Response。如果您再次尝试发送,或者尝试发送带有头的任何其他响应,您将得到一个 HeadersSent 异常。

HTTP 请求

实例化

使用 Manager 创建新的 HTTP 请求。

<?php
$request = $http->newRequest();

设置和获取头和 Cookie

您可以通过与上面描述的 Response 对象相同的方式设置和获取头和 Cookie。

设置和获取内容

您可以通过与上面描述的 Response 对象相同的方式设置和获取内容。

注意:只有在请求方法是 POSTPUT 时才会发送内容。

如果 Request 内容是字符串,则直接发送。

如果 Request 内容是文件资源,则从磁盘读取并发送。

如果内容是数组,则将其转换为 x-www-form-urlencodedmultipart/form-data。数组可以指定上传的文件,通过在数组值前加 @ 来指定。

警告:请确保对用户数据进行清理,以确保只有打算作为文件上传的值以 @ 开头。

<?php
// set content directly as a string
$request->setContent(json_encode([
    'foo' => 'bar',
    'baz' => 'dib',
]));

// set content to a file to be be streamed out
$fh = fopen('/path/to/file');
$request->setContent($fh);

// set content to an array of data, which will be converted
// to x-www-form-urlencoded or multipart/form-data.
$request->setContent([
    'foo' => 'bar',
    'baz' => 'dib',
]);

// set content to an array of data with files to be uploaded
// (note the use of '@' to indicate a file).
$request->setContent([
    'foo' => 'bar',
    'baz' => 'dib',
    'zim' => '@/path/to/file'
]);

设置 URL 和方法

要设置 URL 和方法,请执行以下操作

<?php
use Aura\Http\Message\Request;
$request->setUrl('http://example.com');
$request->setMethod(Request::METHOD_POST);

(默认情况下,所有请求最初都使用 Aura\Http\Message\Request::METHOD_GET 方法。)

设置身份验证

要设置身份验证凭据,选择身份验证类型,然后设置用户名和密码。

<?php
use Aura\Http\Message\Request;
$request->setAuth(Request::AUTH_BASIC);
$request->setUsername('username');
$request->setPassword('password');

可用的身份验证类型是 Aura\Http\Message\Request::AUTH_BASICAura\Http\Message\Request::AUTH_DIGEST

发送请求

您可以通过 Manager 对象发送请求;它返回一个 ResponseStack

<?php
$stack = $http->send($request);
// $stack[0]->headers contains the headers of the last response
// $stack[0]->content contains the content of the last response

$stack 是一个包含所有响应(包括重定向)的 Aura\Http\Message\Response\Stack。栈顺序是后进先出。栈中的每个项都是一个 Aura\Http\Message\Response 对象。

更多示例

向 GitHub API 发送 GET 请求以列出 Aura 的仓库

<?php
$request->setUrl('https://api.github.com/orgs/auraphp/repos');
$request->getHeaders()->add('User-Agent', 'Aura Bot v1');
$stack = $http->send($request);
$repos = json_decode($stack[0]->content);
foreach ($repos as $repo) {
    echo $repo->name . PHP_EOL;
}

发送自定义 POST 请求

<?php
use Aura\Http\Message\Request;
$request->setUrl('http://example.com/submit.php');
$request->setMethod(Request::METHOD_POST);
$request->setContent(json_encode(['hello' => 'world']));
$request->headers->set('Content-Type', 'application/json');
$stack = $http->send($request);

将响应内容保存到文件

<?php
$fp = fopen('/path/to/download.ext', 'wb+');
$request->setUrl('http://example.com/download.ext');
$request->setSaveToStream($fp);
$stack = $http->send($request);
// $stack[0]->content will be a file stream

HTTP 传输和适配器

HTTP Manager 使用 Transport 对象发送请求。您可以指定传输的各种选项。

// use a cookie jar for all requests
$http->transport->options->setCookieJar('/path/to/cookie.jar');

// the maximum number of request redirects
$http->transport->options->setMaxRedirects(10);

// the request timeout in seconds
$http->transport->options->setTimeout(10);

// the proxy host, port, username, and password
$http->transport->options->setProxy('proxy.example.com');
$http->transport->options->setProxyPort('12345');
$http->transport->options->setProxyUsername('username');
$http->transport->options->setProxyPassword('password');

// ssl options
$http->transport->options->setSslCafile('/path/to/cafile');
$http->transport->options->setSslCapath('capath');
$http->transport->options->setSslLocalCert('/path/to/local.crt');
$http->transport->options->setSslPassphrase('passphrase');
$http->transport->options->setSslVerifyPeer(true);

传输使用 Adapter 来处理实际发送请求。有两个适配器可用

  • Aura\Http\Request\Adapter\Curl,当加载 curl 扩展时自动使用。此适配器将文件资源直接从磁盘流到磁盘,而无需将整个文件加载到内存中。

  • Aura\Http\Request\Adapter\Stream,这是在未加载 curl 时的后备。此适配器不适合发送或接收大文件。每个文件都将加载到内存中。这是 PHP HTTP 流的限制。