nathanmac/laravel-restclient

Laravel 4的简单Rest客户端

dev-master 2017-01-16 17:26 UTC

This package is not auto-updated.

Last update: 2024-09-14 15:32:19 UTC


README

Build Status Still Maintained

Laravel 4的简单Rest客户端包

安装

首先通过Composer安装此包。编辑项目的composer.json文件,以添加Nathanmac/laravel-restclient依赖。

"require": {
	"nathanmac/laravel-restclient": "dev-master"
}

然后,在终端中更新Composer

composer update

此操作完成后,最后一步是添加服务提供者。打开app/config/app.php,并向提供者数组中添加新项。

'Nathanmac\RestClient\RestClientServiceProvider'
调用端点
try {
    $response = RestClient::get('hostname:port/endpoint');
} catch (Exception $ex) {
    print "Error: " . $ex->getMessage(); // Error: COULDNT_RESOLVE_HOST
}
HTTP方法
  $response = RestClient::get('hostname:port/endpoint');
  $response = RestClient::post('hostname:port/endpoint', 'payload data');
  $response = RestClient::put('hostname:port/endpoint', 'payload data');
  $response = RestClient::delete('hostname:port/endpoint');
添加HTTP头
$headers = array(
    'token: SLDKFJLKSDFJSLDFJ',
    'other: asfasdfasdf'
);

$response = RestClient::get('hostname:port/endpoint', $headers);
$response = RestClient::post('hostname:port/endpoint', 'payload data', $headers);
$response = RestClient::put('hostname:port/endpoint', 'payload data', $headers);
$response = RestClient::delete('hostname:port/endpoint', $headers);
获取HTTP状态码
echo "HTTP Status Code: " . $response->getStatusCode(); // HTTP Status Code: 200
echo "HTTP Status Text: " . $response->getStatusText(); // HTTP Status Text: OK
返回响应内容
print $response->getContent();
返回响应头
print_r($response->getHeaders());
返回特定头
echo "Content-Type: " . $response->getHeader('content_type'); // Content-Type: application/json
返回响应时间(秒)
echo "Time: " . $response->getTime();  // Time: 0.23453
为每个请求添加自定义cURL选项

首先发布配置文件

php artisan config:publish nathanmac/laravel-restclient

然后编辑app/config/packages/nathanmac/laravel-restclient/config.php中的options数组。