novotnyj/http-helper

面向对象的PHP cURL库。

2.0.0 2015-04-26 18:54 UTC

This package is not auto-updated.

Last update: 2024-09-28 15:03:18 UTC


README

这个PHP库是为了替代pecl_http而创建的。目标是使使用cURL更加简单和面向对象。

基本方法名称与pecl_http HttpRequest相似。这应该使在pecl_http和HttpHelper之间切换变得更加容易。

HttpHelper\Request使用cURL - 确保您在php.ini中启用了cURL扩展

要求

HttpHelper需要PHP 5.3.1或更高版本,并且已安装php5-curl。

安装

HttpHelper可以使用Composer安装。此包可在Packagist仓库中找到。

composer require novotnyj/http-helper

使用示例

GET请求

您可以发送类似于pecl_http的HTTP请求

use HttpHelper\Request;

$request = new Request("http://www.google.com");
$request->send();
if ($request->getResponseCode() == 200) {
	echo $request->getResponseBody();
}

或者,您可以使用send方法返回的HttpHelper\Response对象。同时,在send方法出错的情况下,将send方法包裹在try/catch块中

...
try {
	$response = $request->send();
	if ($response->getCode() == 200) {
		echo $response->getBody();
	}
} catch (RequestException $e) {
	echo $e->getMessage();
}

POST请求

要发送POST请求,请将方法更改为POST

use HttpHelper\Request;

$request = new Request("http://www.foo.com/sign/in", Request::POST);
$request->setPostFields(array(
	'login' => 'user',
	'password' => 'p4ssW0rd'
));
try {
	$response = $request->send();
	if ($response->getCode() == 200) {
		echo $response->getBody();
	}
} catch (RequestException $e) {
	echo $e->getMessage();
}

要使用POST请求发送文件

...
$request->setMethod(Request::POST);
$request->setPostFields(array(
	'upload' => '@/absolute/path/to/file.ext'
));
...

要发送JSON POST请求

...
$request->setMethod(Request::POST);
$request->setJSON(array(
	'login' => 'foo'
));
...

跟随重定向

要启用自动跟随Location头(对于301、302和303响应代码)

...
$request->enableRedirects();
...

默认情况下,这将仅跟随Location 20次。之后,send方法将引发RequestException。您可以将不同的限制作为enableRedirects的参数传递以启用重定向(0表示无限次跟随Location)。要跟随Location 999次

$request->enableRedirects(999);

注意:此函数不使用CURLOPT_FOLLOWLOCATION,因此即使在您的php.ini中设置了open_basedir或safe_mode,您也应该没问题。

使用响应cookie

要启用自动使用响应cookie进行下一次请求

...
$request->enableCookies();
...

注意:尚未实现根据过期日期过滤响应cookie。