PHP REST 客户端 API 调用

标签 php json api rest curl

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

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

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

谢谢!

最佳答案

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

  1. 使用CURL

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);
  1. 使用Guzzle

这是一个“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
  1. 使用file_get_contents

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

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

如果 $response 是 JSON,使用 json_decode 把它变成 php 数组:

$response = json_decode($response);
  1. 使用Symfony's 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
}
  1. 使用HTTPFUL

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

Httpful 包括...

  • 可读的 HTTP 方法支持(GET、PUT、POST、DELETE、HEAD 和 OPTIONS)
  • 自定义 header
  • 自动“智能”解析
  • 自动负载序列化
  • 基本授权
  • 客户端证书授权
  • 请求"template"

例如

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

该库注意到响应中的 JSON 内容类型,并自动将响应解析为 native 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";

关于PHP REST 客户端 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10487331/

相关文章:

jquery - 循环动态 JSON 字符串

image - 有没有可以让我按图像搜索的API?

java - 基于 Java 的应用程序的发现机制 API

php - 如何创建网站 API

python - OpenCV(在 C++ 中)到 MQTT 代理

javascript - $.get jquery 函数返回完整的 html 页面而不是数据中的 json

php使用ajax后无法连接数据库

php - 是否可以使用 PDO 在插入中嵌入 select 语句

java - 通过 REST 调用使用外键将项目添加到集合中

php 不向数据库发送消息