技術めも

Guzzle めも

http://docs.guzzlephp.org/en/latest/index.html
http://qiita.com/yousan/items/2a4d9eac82c77be8ba8b

comporser.json

"require": {
    "guzzlehttp/guzzle": "*"
}

Basic

$client = new GuzzleHttp\Client();
$res = $client->request('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"...'

// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});
$promise->wait();

リクエストヘッダ設定

$headers = ['User-Agent' => 'Mozilla/5.0'];
$response = $client->request('GET', $path, [
    'allow_redirects' => true,
    'headers' => $headers,
    //'form_params' => $form_params,
]);
$response_body = (string) $response->getBody();
echo $response_body;

Guzzle ラップクラス

使い方

$httpClient = new HttpClient();

list($httpCode, $httpBody) = $httpClient->get($url);

list($httpCode, $httpBody) = $httpClient->post($url, ['name1' => 'value1', ... ]);

CODE

<?php
/**
 * GuzzleHttp Client Class
 */

class HttpClient
{
    private $client = null;
    private $response = null;
    private $options = [];

    public function __construct($baseUrl = null, $timeout = null)
    {
        $options = [];
        if ($baseUrl !== null) {
            $uri = parse_url($baseUrl);
            $options['base_uri'] = $uri['scheme'].'://'.$uri['host'];
        }
        if ($timeout !== null) {
            $options['timeout'] = $timeout;
        }
        // default setting
        $options['allow_redirects'] = true;
        $options['cookies'] = true;
        $options['headers'] = $this->requestHeaders();
        $this->client = new \GuzzleHttp\Client($options);
    }

    public function setRequestHeader($key, $val)
    {
        if (empty($this->options['headers'])) $this->options['headers'] = [];
        $this->options['headers'][$key] = $val;
    }

    public function setTimeout($val)
    {
        $this->options['timeout'] = $val;
    }

    public function setSslVerify($isCheck)
    {
        $this->options['verify'] = $isCheck;
    }

    public function setOption($key, $val)
    {
        $this->options[$key] = $val;
    }

    public function get($path)
    {
        $this->response = [];
        try {
            $this->response = $this->client->request('GET', $path, $this->options);
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            return [(int)$e->getCode(), null];
        } catch (\GuzzleHttp\Exception\ConnectException $e) {
            return [0, null]; // timeout
        }

        $resCode = (int)$this->response->getStatusCode();
        $resBody = (string)$this->response->getBody();

        return [$resCode, $resBody];
    }

    // @see: http://docs.guzzlephp.org/en/latest/quickstart.html#post-form-requests
    public function post($path, $params = [])
    {
        $this->response = [];
        $this->options['form_params'] = $params;
        try {
            $this->response = $this->client->request('POST', $path, $this->options);
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            return [(int)$e->getCode(), null];
        } catch (\GuzzleHttp\Exception\ConnectException $e) {
            return [0, null]; // timeout
        }

        $this->options['form_params'] = []; // POSTデータ初期化
        $resCode = (int)$this->response->getStatusCode();
        $resBody = (string)$this->response->getBody();

        return [$resCode, $resBody];
    }

    public function getResponseHeader($key)
    {
        if (empty($this->response)) return null;
        if (empty($this->response->getHeader($key))) return null;
        return $this->response->getHeader($key);
    }

    public function getResponseHeaders()
    {
        if (empty($this->response)) return null;
        return $this->response->getHeaders();
    }

    private function requestHeaders()
    {
        return [
            'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding' => 'gzip, deflate, sdch',
            'Accept-Language' => 'ja,en-US;q=0.8,en;q=0.6',
            'Cache-Control' => 'no-cache',
            'Connection' => 'keep-alive',
            'Pragma' => 'no-cache',
            'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
        ];
    }
}