PHP REST 客户端 API 调用


PHP REST client API call

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

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

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

谢谢!

有多种

方法可以调用 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);
    使用咕噜
  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
  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的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(
  • 自定义标头
  • 自动"智能"解析
  • 自动有效负载序列化
  • 基本身份验证
  • 客户端证书身份验证
  • 请求"模板">

前任。

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

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

如果启用了 fopen 包装器,您可以使用file_get_contents。请参阅:http://php.net/manual/en/function.file-get-contents.php

如果不是,并且由于主机不允许而无法修复,则cURL是一个很好的使用方法。

您可以使用:

$result = file_get_contents( $url );

http://php.net/manual/en/function.file-get-contents.php