4

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

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

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

谢谢!

4

3 回答 3

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);
  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 的 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 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";
于 2015-12-08T07:53:39.763 回答
2

您可以使用:

$result = file_get_contents( $url );

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

于 2012-05-07T18:46:02.957 回答
2

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

如果它们不是,并且您无法修复它,因为您的主机不允许它,那么这cURL是一个很好的使用方法。

于 2012-05-07T18:46:48.440 回答