【问题标题】:How to get Facebook Page info using Guzzle如何使用 Guzzle 获取 Facebook 页面信息
【发布时间】:2015-07-14 15:26:25
【问题描述】:

我确定我错过了什么,但目前我不明白是什么。

我正在玩 Guzzle,我正在尝试获取页面信息:

<?php

/**
 * Example of usage of APIConnect to get information
 * about a Facebook Page through Graph API.
 */

require('../vendor/autoload.php');

/** SET HERE A PAGE */
$page = 'SamplePage';

$remoteUrl = 'https://graph.facebook.com/' . $page;

$client = new GuzzleHttp\Client();
$res = $client->get($remoteUrl);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'

这是 Guzzle 文档显示的代码。

现在,我希望调用此代码会返回一些对象,这些对象在其属性之一中包含以下 JSON 响应,因为如果我直接在浏览器中调用 URL,我会收到该响应:

{
   "error": {
      "message": "An access token is required to request this resource.",
      "type": "OAuthException",
      "code": 104
   }
}

为什么相反,如果我使用 Guzzle 方法获取响应值,我看到的是 null?我错过了什么?

【问题讨论】:

    标签: php curl guzzle


    【解决方案1】:

    好的,我解决了这个问题。

    第一个问题是我使用的是旧版本的 Guzzle。

    在我的 composer.json 我有这个:

    ## THIS IS WRONG ##
    "require": {
        "guzzlehttp/guzzle": "*@stable"
    },
    

    但是这样我下载了Guzzle 3,那是一个旧版本。

    To download the new version (the 6),我是这样改行的:

    ## THIS IS CORRECT ##
    "require": {
        "guzzlehttp/guzzle": "~6"
    },
    

    所以,我现在有 Guzzle 6。

    还必须更改代码。这是正确的版本:

    <?php
    
    /**
     * Example of usage of APIConnect to get information
     * about a Facebook Page through Graph API.
     */
    
    require('../vendor/autoload.php');
    
    use GuzzleHttp\Client;
    use GuzzleHttp\Exception\RequestException;
    
    $url = 'https://graph.facebook.com/SamplePage'; // Set the URL
    $api_end_point = '';
    $end_point = '';
    
    $client = new Client(
        ['base_uri' => $url]
        );
    
    $path = $api_end_point . $end_point;
    echo $path;
    
    try
    {
        $res = $client->get($path);
    }
    catch (RequestException $e)
    {
        $res = $e->getRequest();
    
        if ($e->hasResponse())
        {
            $res = $e->getResponse();
        }
    }
    
    echo $res->getStatusCode();
    // "400"
    print_r($res->getHeader('content-type'));
    // Array ( [0] => text/javascript; charset=UTF-8 )
    echo $res->getBody();
    // {"error":{"message":"An access token is required to request this resource.","type":"OAuthException","code":104}}
    

    现在 Guzzle 返回响应。这是一个 400 状态码,因为我们需要身份验证,但这是另一个问题 :)

    【讨论】:

      猜你喜欢
      • 2014-01-24
      • 1970-01-01
      • 2016-09-25
      • 2015-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多