facebook twitter hatena line email

Php/laravel/laravel5/guzzle

提供: 初心者エンジニアの簡易メモ
2017年11月30日 (木) 16:55時点におけるAdmin (トーク | 投稿記録)による版 (参考)

移動: 案内検索

guzzleとは

httpリクエスト用ライブラリ

guzzleインストール

composer require guzzlehttp/guzzle

確認

vi composer.json
   "require": {
       "guzzlehttp/guzzle": "^6.2"
   }

サンプル

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
$client = new Client(); //GuzzleHttp\Client
$result = $client->post('your-request-uri', [
    'form_params' => [
        'sample-form-data' => 'value'
    ]
]);

ログイン(画面遷移)サンプル

cookiesをtrueにしておく

 $base_url = 'http://example.com';
 $client = new \GuzzleHttp\Client( [
     'base_uri' => $base_url,
     'cookies' => true
 ] );
 $path = "/myaccount/login";
 $headers = [
       'Origin'                    => 'http://example.com',
       'Accept-Encoding'           => 'gzip, deflate, br',
       'Accept-Language'           => 'ja,en-US;q=0.8,en;q=0.6',
       'Upgrade-Insecure-Requests' => '1',
       'User-Agent'                => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36',
       'Content-Type'              => 'application/x-www-form-urlencoded',
       'Accept'                    => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
       'Cache-Control'             => 'max-age=0',
       'Referer'                   => 'http://example.com',
       'Connection'                => 'keep-alive'
     ];
 $response = $client->get($path,
     [
         'allow_redirects' => true,
         'headers'         => $headers,
     ]
 );
 $response = $client->post($path ,
     [
         'allow_redirects' => true,
         'headers'         => $headers,
         'form_params'     => [
             'id' => "1234",
             'pass' => "hogehoge",
         ]
     ]
 );
 $response_body = (string) $response->getBody()->getContents();
 echo $response_body;

guzzleでxmlを送信

$request = new Request(
    'POST',-
    $url,
    ['Content-Type' => 'text/xml; charset=UTF8'],
    $xml
);

参考

https://medium.com/laravel-5-the-right-way/using-guzzlehttp-with-laravel-1dbea1f633da

http://qiita.com/yousan/items/2a4d9eac82c77be8ba8b