作为程序员一定要保持良好的睡眠,才能好编程

php中httpClient相关类库

发布时间:2019-03-25

近期在学习swoole的过程中,有人说  swoole的 client 可以用于 同步阻塞的模型中,如果只是为了使用swoole的client,那么就没有必要使用swoole了,还是让swoole乖乖的运行在cli下吧。


httpClient 中都有哪些成熟的框架呢?我再github上搜索了一下,还真多,


java的


c的


c++的


php的,


下面我们着重说说php的httpClient ,


/guzzle


https://github.com/guzzle/guzzle
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');

echo $response->getStatusCode(); # 200
echo $response->getHeaderLine('content-type'); # 'application/json; charset=utf8'
echo $response->getBody(); # '{"id": 1420053, "name": "guzzle", ...}'


//发送异步请求  功能还是比较强大的哦。
# Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});

$promise->wait();



/httpclient

use hightman\http\Client;

$http = new Client();

// 1. display response contents
echo $http->get('http://www.baidu.com');
echo $http->get('http://www.baidu.com/s', ['wd' => 'php']);

// 2. capture the response object, read the meta information
$res = $http->get('http://www.baidu.com');
print_r($res->getHeader('content-type'));
print_r($res->getCookie(null));

// 3. post request
$res = $http->post('http://www.your.host/', ['field1' => 'value1', 'field2' => 'value2']);
if (!$res->hasError()) {
   echo $res->body;    // response content
   echo $res->status;  // response status code
}

// 4. head request
$res = $http->head('http://www.baidu.com');
print_r($res->getHeader(null));

// delete request
$res = $http->delete('http://www.your.host/request/uri');

// 5. restful json requests
// there are sismilar api like: postJson, putJson
$data = $http->getJson('http://www.your.host/request/uri');
print_r($data);

$data = $http->postJson('http://www.your.host/reqeust/uri', ['key1' => 'value1', 'key2' => 'value2']);


curl/curl

这个插件是对 curl 命令的一个封装的php类库,使用简单方便、快捷。