PHP REST 客户端 API 调用

EsT*_*eGe 4 php api rest json curl

我想知道,是否有一种简单的方法来执行 REST API GET 调用?我一直在阅读有关 cURL 的文章,但这是一个好方法吗?

我也遇到过 php://input 但我不知道如何使用它。有没有人给我举个例子?

我不需要高级 API 客户端的东西,我只需要对某个 URL 执行 GET 调用来获取一些将由客户端解析的 JSON 数据。

谢谢!

Som*_*luk 7

有多种方法可以进行 REST 客户端 API 调用:

  1. 使用卷曲

CURL 是最简单和好方法。这是一个简单的调用

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA);
$result = curl_exec($ch);

print_r($result);
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)
  1. 使用狂饮

它是一个“PHP HTTP 客户端,可以轻松使用 HTTP/1.1 并消除使用 Web 服务的痛苦”。使用 Guzzle 比使用 cURL 容易得多。

以下是来自网站的示例:

$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', [
    'auth' =>  ['user', 'pass']
]);
echo $res->getStatusCode();           // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody();                 // {"type":"User"...'
var_export($res->json());             // Outputs the JSON decoded data
Run Code Online (Sandbox Code Playgroud)
  1. 使用file_get_contents

如果你有一个 url 并且你的 php 支持它,你可以调用 file_get_contents:

$response = file_get_contents('http://example.com/path/to/api/call?param1=5');
Run Code Online (Sandbox Code Playgroud)

如果 $response 是 JSON,则使用 json_decode 将其转换为 php 数组:

$response = json_decode($response);
Run Code Online (Sandbox Code Playgroud)
  1. 使用Symfony 的 RestClient

如果您使用的是 Symfony,则有一个很棒的 rest 客户端包,它甚至包含所有 ~100 个异常并抛出它们而不是返回一些无意义的错误代码 + 消息。

try {
    $restClient = new RestClient();
    $response   = $restClient->get('http://www.someUrl.com');
    $statusCode = $response->getStatusCode();
    $content    = $response->getContent();
} catch(OperationTimedOutException $e) {
    // do something
}
Run Code Online (Sandbox Code Playgroud)
  1. 使用HTTPFUL

Httpful 是一个简单的、可链接的、可读的 PHP 库,旨在使 HTTP 说话变得理智。它让开发人员专注于与 API 交互,而不是筛选 curl set_opt 页面,并且是理想的 PHP REST 客户端。

Httpful 包括...

  • 可读的 HTTP 方法支持(GET、PUT、POST、DELETE、HEAD 和 OPTIONS)
  • 自定义标题
  • 自动“智能”解析
  • 自动有效载荷序列化
  • 基本认证
  • 客户端证书认证
  • 请求“模板”

前任。

发送 GET 请求。获取自动解析的 JSON 响应。

该库会注意到响应中的 JSON Content-Type 并自动将响应解析为原生 PHP 对象。

$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";
$response = \Httpful\Request::get($uri)->send();

echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";
Run Code Online (Sandbox Code Playgroud)