【问题标题】:Learning how to access data from an API using Guzzle学习如何使用 Guzzle 从 API 访问数据
【发布时间】:2016-01-12 02:27:47
【问题描述】:

我正在构建一个需要使用 API 的新应用程序,尤其是使用 OAuth 的应用程序,但首先我尝试使用一个简单的 API 来了解如何在应用程序,因为我以前从未使用过 API。

我正在我的本地主机上运行一个全新的 Laravel 5.1 项目,并安装了 Guzzle 库。

按照Guzzle documentation 的说明,我相信我已正确设置,但我无法对收到的回复做出头脑或故事。

我尝试使用的 API 是 http://freegeoip.net/,发出请求的格式是 freegeoip.net/{format}/{IP_or_hostname}

我已经设置了一个页面,我可以在其中输入 IP 地址并提交它,然后它由我的控制器中的以下函数运行:

public function retrieve(Request $request)
    {
        $url = "http://freegeoip.net/json/" . $request->ipaddress;
        $client = new Client();
        $response = $client->request('GET', $url);
        dd($response);
    }

我的路线和一切都设置正确,我在控制器顶部引用 Guzzle:

use GuzzleHttp\Client;

但是我从dd($response); 得到的回复对我来说没有任何意义,也没有暗示我如何从中获取任何信息。

这是dd($response) 输出的内容

Response {#195 ▼
  -reasonPhrase: "OK"
  -statusCode: 200
  -headers: array:8 [▶]
  -headerLines: array:8 [▶]
  -protocol: "1.1"
  -stream: Stream {#186 ▶}
}

但是当我通过浏览器运行等效的 URL 时,我得到了

{"ip":"202.21.xxx.xxx","country_code":"NZ","country_name":"New Zealand","region_code":"WGN","region_name":"Wellington","city":"Wellington","zip_code":"6011","time_zone":"Pacific/Auckland","latitude":-41.283,"longitude":174.784,"metro_code":0}

谁能帮助我解决我做错了什么,或者指出一些关于如何开始在 Laravel 中使用 API 的好资源。关于如何构建 Laravel API 的内容很多,但没有关于如何从 Laravel 访问 API。

【问题讨论】:

    标签: php api laravel laravel-5.1 guzzle


    【解决方案1】:

    经过大量挖掘,我发现我只是想念json_decode()

    当我运行它时,请求工作正常:

    public function retrieve(Request $request)
        {
            $url = "http://freegeoip.net/json/" . $request->ipaddress;
            $client = new Client();
            $response = $client->request('GET', $url);
            dd(json_decode($response->getBody()));
        }
    

    为以后遇到此类问题的其他人回答这个问题:)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      相关资源
      最近更新 更多