2018-04-01 04:57:30 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Support;
|
|
|
|
|
|
|
|
use GuzzleHttp\Client;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Helper for HTTP stuff
|
|
|
|
*/
|
|
|
|
class Http
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Download a URI. If a file is given, it will save the downloaded
|
|
|
|
* content into that file
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-04-01 04:57:30 +08:00
|
|
|
* @param $uri
|
|
|
|
* @param array $opts
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-04-04 22:04:14 +08:00
|
|
|
* @throws \GuzzleHttp\Exception\GuzzleException
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
|
|
|
* @return string
|
2018-04-01 04:57:30 +08:00
|
|
|
*/
|
|
|
|
public static function get($uri, array $opts)
|
|
|
|
{
|
2018-05-15 00:20:38 +08:00
|
|
|
$opts = array_merge([
|
|
|
|
'connect_timeout' => 2, // wait two seconds by default
|
|
|
|
], $opts);
|
|
|
|
|
2018-04-01 04:57:30 +08:00
|
|
|
$client = new Client();
|
|
|
|
$response = $client->request('GET', $uri, $opts);
|
|
|
|
|
|
|
|
$body = $response->getBody()->getContents();
|
|
|
|
if ($response->getHeader('content-type') === 'application/json') {
|
|
|
|
$body = \GuzzleHttp\json_decode($body);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $body;
|
|
|
|
}
|
|
|
|
}
|