ptcong/easyrequest

此包已被弃用且不再维护。未建议替代包。

一个轻量级的PHP http客户端,实现PSR7,使用socket/curl发送请求。

1.0.6 2016-12-04 14:06 UTC

This package is not auto-updated.

Last update: 2018-07-16 13:03:01 UTC


README

一个轻量级的PHP http客户端,实现PSR7,使用socket/curl发送请求。

特性

  • 与其他库相同的所有通用特性
  • 上传大文件(大于2GB)
  • 支持HTTP代理、SOCKS4、SOCKS4A、SOCKS5(CURL和Socket处理器)。
  • 使用PSR-7 http消息

要求

  • 启用Socket或安装curl扩展
  • PHP 5.3+

安装

composer require ptcong/easyrequest:^1.0

有时你不想使用composer,只想包含一个文件,就像我们旧的库一样(ptcong/php-http-client)。运行 build/run.php 脚本以获取 compiled.php 文件,并在脚本顶部包含它。

使用方法

创建请求

Client::request 方法仅创建 \EasyRequest\Client 类的新实例。

$request = \EasyRequest\Client::request('https://google.com');
$request = \EasyRequest\Client::request('https://google.com', 'GET', $options);
$request = \EasyRequest\Client::request('https://google.com', 'POST', $options);

// then
$request->send();
// or
$request = \EasyRequest\Client::request('https://google.com')->send();

带有默认选项

$request = \EasyRequest\Client::request('https://google.com', 'POST', array(
    'protocol_version' => '1.1',
    'method'           => 'GET',
    'header'           => array(),
    'body'             => '',
    'body_as_json'     => false,
    'query'            => array(),
    'form_params'       => array(),
    'multipart'        => array(),
    'default_header'   => true,    // add general headers as browser does
    'upload'           => false,   // wanna upload large files ?
    'cookie_jar'       => null,    // file path or CookieJarInterface

    'bindto'           => null,    // bind to an interface (IPV4 or IPV6), same as CURLOPT_INTERFACE
    'proxy'            => null,
    'proxy_type'       => null,
    'proxy_userpwd'    => null,
    'auth'             => null,

    'timeout'          => 10,      // connect timeout
    'nobody'           => false,   // get header only, you also can use HEAD method
    'follow_redirects' => false,   // boolean or integer (number of max follow redirect)
    'handler'          => null,    // handler for sending request
    'curl'             => array(), // use more curl options ?
));

设置请求选项

withOption 方法将覆盖现有选项。如果您想向当前选项追加查询字符串、表单参数,请参阅下文。

$request = \EasyRequest\Client::request('https://google.com', 'GET', array(
    'follow_redirects' => 3,
    'query'            => 'a=b&c=d'
));

// or
$request->withOption('follow_redirects', 3);

// or
$request->withOption(array(
    'follow_redirects' => 3,
    'query'            => 'a=b&c=d'
));

快速请求

此方法将创建新请求并立即发送,您无需在此处调用 send() 方法。

$response = \EasyRequest\Client::get('https://google.com', 'GET', array(
    'follow_redirects' => 3,
    'query'            => 'a=b&c=d'
));

$response = \EasyRequest\Client::post('https://google.com', ...);
$response = \EasyRequest\Client::head('https://google.com', ...);
$response = \EasyRequest\Client::patch('https://google.com', ...);
$response = \EasyRequest\Client::delete('https://google.com', ...);

... more 

向请求中添加头部

$request = \EasyRequest\Client::request('https://google.com', 'GET', array(
    'header' => array(
        'User-Agent' => 'Firefox 45',
        'Cookie' => 'cookie1=value1; cookie2=value2;',
        'Example' => array(
            'value 1',
            'value 2'
        )
    ),
));

// you also can use PSR7 as
$request = \EasyRequest\Client::request('https://google.com')
    ->withHeader('User-Agent', 'Firefox 45')
    ->withHeader('Example', array('value1', 'value 2'));

处理cookie

您可以使用 header 选项添加cookie,如上所述,但我们已经有了 CookieJar 来为您处理cookie。默认情况下,如果未设置cookie_jar,则客户端类将在发送请求之前自动创建一个 CookieJar 实例。您可以选择

  • FileCookieJar 将cookie写入文件,就像浏览器一样,下一个请求将使用此文件中的cookie。
  • SessionCookieJar 将cookie写入 $_SESSION(记住,您已经在脚本顶部添加了 session_start())
  • CookieJar 仅将cookie写入数组,如果您的脚本运行完成,则所有cookie都将丢失。
$jar = new \EasyRequest\Cookie\CookieJar;
// or
$jar = new \EasyRequest\Cookie\FileCookieJar($filePath);
// or
$jar = new \EasyRequest\Cookie\SessionCookieJar;

// add cookie from string of multiple cookies
$jar->fromString('cookie1=value1; cookie2=value2');

// add cookie with more information 
$jar->add(Cookie::parse('cookie2=value2; path=/; domain=abc.com')); 

// add cookie from \Psr\Http\Message\ResponseInterface
$jar->fromResponse($response);

// read more at \EasyRequest\Cookie\CookieJarInterface

$request = \EasyRequest\Client::request('https://google.com', 'GET', array(
    'cookie_jar' => $jar
))->send();

获取响应cookie

var_dump($jar->toArray());
// or
var_dump($request->getOption('cookie_jar')->toArray());

var_dump((string) $jar);

您可以使用 $jar->getFor($domain, $path) 方法获取特定域名和路径的cookie。此方法将创建一个包含您的cookie的新 CookieJar 实例

var_dump($jar->getFor($domain, $path));

添加查询字符串

$options = array(
    'query' => 'a=b&c=d'
);
// or
$options = array(
    'query' => array(
        'a' => 'b',
        'c' => 'd',
        'x' => array(
            'y', 'z'
        ),
        'x2' => array(
            'y2' => 'z2'
        )
    )
);
$request = \EasyRequest\Client::request('https://google.com', 'GET', $options);

或者你可以使用 withQuery 方法,这是一个动态方法,可以处理一些情况

    /**
     * Add query string to request.
     *
     * @param  string|array $name      This value may be:
     *                                 - a query string
     *                                 - array of query string
     * @param  null|string  $value
     * @param  bool         $append
     * @param  bool         $recursive
     * @return self
     */
    $request->withQuery($name, $value = null, $append = true, $recursive = false);


$request->withQuery(array(
    'a' => 'b',
    'c' => 'd',
    'x' => array(
        'y', 'z'
    ),
    'x2' => array(
        'y2' => 'z2'
    )
));
// or
$request->withQuery('query=value1&key2=value2');
// or
$request->withQuery('query', 'value1');
// if you want to clear all existing query and add new, just use false for $append
$request->withQuery('query', 'value1', false);

添加表单参数

这与 添加查询字符串 相似

你可以使用与 withQuery 相同的 withFormParam 方法

    /**
     * Add form param to request.
     *
     * @param  string|array $name      This value may be:
     *                                 - query string
     *                                 - array of query string
     * @param  null|string  $value
     * @param  bool         $append
     * @param  bool         $recursive
     * @return self
     */
    public function withFormParam($name, $value = null, $append = true, $recursive = false)

添加多部分数据

每个多部分部分需要 namecontents

$request = \EasyRequest\Client::request('https://google.com', 'GET', array(
    'multipart' => array(
        array(
            'name'     => 'input1',
            'contents' => 'value1'
        ),
        array(
            'name'     => 'input1',
            'contents' => 'value1',
            'filename' => 'custom file name.txt'
            'headers'  => array('Custom-header' => 'value'),
        )
    ),
));

// you also can use
$request
    ->withMultipart('field2', 'value2')
    ->withMultipart('field3', 'value3', 'fieldname3')
    ->withMultipart('field4', 'value4', 'fieldname4', array('Custom-Header' => 'value'))
    ->withMultipart('file5', fopen('/path/to/file'), 'filename1') // to upload file

上传文件

你可以使用多部分选项来上传文件,但使用此方法更简单。

$request
    ->withFormFile('file1', '/path/to/file1', $optionalFileName = null, $optionalHeaders = array())
    ->withFormFile('file2', '/path/to/file2');

发送原始数据

$request->withBody('raw data');

发送 JSON 数据

用于轻松上传作为请求主体的 JSON 编码数据。如果消息上尚未存在 Content-Type 标头,将添加 Content-Type: application/json 标头。

$request->withJson(array(1,2,3));
// or
$request->withJson(json_encode(array(1,2,3)));

使用代理

你可以使用 HTTP 或 SOCKS4、SOCKS4A、SOCKS5 代理。

$request = \EasyRequest\Client::request('http://domain.com', 'POST', array(
    'proxy'         => '192.168.1.105:8888',
    'proxy_userpwd' => 'user:pass',
    'proxy_type'    => Client::PROXY_SOCKS5, // if not given, it will use this proxy as HTTP_PROXY
));

$request->withProxy('192.168.1.105:8888', 'user:pass', Client::PROXY_SOCKS5);
$request->withProxy('192.168.1.105:8888', null, Client::PROXY_SOCKS4);
$request->withProxy('192.168.1.105:8888', null, Client::PROXY_HTTP);

$request->withSocks4Proxy('192.168.1.105:8888'); 
$request->withSocks5Proxy('192.168.1.105:8888', 'user:pass'); 
$request->withHttpProxy('192.168.1.105:8888', 'user:pass'); 

基本认证

$request = \EasyRequest\Client::request('http://domain.com', 'POST', array(
    'auth' => 'user:pass',
));

将请求绑定到接口

$request = \EasyRequest\Client::request('http://domain.com', 'POST', array(
    'bindto' => '123.123.123.123', // same as CURLOPT_INTERFACE option
));

获取响应

$request = \EasyRequest\Client::request('http://domain.com', 'POST');
$response = $request->send();

// Returns \Psr\Http\Message\RequestInterface
var_dump($request->getRequest());

// Returns \Psr\Http\Message\ResponseInterface
// Or null if request is not sent or failure
var_dump($request->getResponse());

var_dump($response);

当使用跟随重定向选项时,有时你可能想获取当前 URL(最后一次重定向的 URL)。

getCurrentUri 方法将返回 \Psr\Http\Message\UriInterface

$request->getCurrentUri();
$response = $request->getResponse();

// you can use PSR7 here
$response->getHeaders();
$response->getHeader('Set-Cookie');
$response->getHeaderLine('Location');

$response->getProtocolVersion();

echo (string) $response->getBody();

获取重定向请求

当使用跟随重定向选项时,有时你想要获取所有请求和响应。

每个请求和响应都遵循 PSR7

var_dump($request->getRequests());

获取响应

var_dump($request->getResponses());

获取调试信息

当请求失败时,你可以使用 $request->getError() 来查看错误消息。

并使用 $request->getDebug() 来查看一些调试信息。