有多种方法可以进行 REST 客户端 API 调用:
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)
它是一个“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)
如果你有一个 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)
如果您使用的是 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)
Httpful 是一个简单的、可链接的、可读的 PHP 库,旨在使 HTTP 说话变得理智。它让开发人员专注于与 API 交互,而不是筛选 curl set_opt 页面,并且是理想的 PHP REST 客户端。
Httpful 包括...
前任。
发送 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)
| 归档时间: |
|
| 查看次数: |
19168 次 |
| 最近记录: |