facebook twitter hatena line email

「Php/laravel/laravel5/guzzle」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(画面遷移サンプル)
(画面遷移サンプル)
行21: 行21:
 
  ]);
 
  ]);
  
==画面遷移サンプル==
+
==ログイン(画面遷移)サンプル==
 
cookiesをtrueにしておく
 
cookiesをtrueにしておく
 
   $base_url = 'http://example.com';
 
   $base_url = 'http://example.com';

2017年6月7日 (水) 00:01時点における版

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;

参考

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

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