本文實例講述了php的http客戶端guzzle簡單使用方法。分享給大家供大家參考,具體如下:
首先來一段官方文檔對guzzle的介紹:
然后cd到網站根目錄,執行composer命令下載guzzle:(linux環境)
1
|
composer require guzzlehttp/guzzle |
下載完成后會生成一個vender文件夾:
在vender同級目錄新建了一個guzzle.php來寫例子。
【get請求】
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?php require './vendor/autoload.php' ; //實例化客戶端 $client = new guzzlehttp\client(); //構造url $url = 'https://www.baidu.com' ; //get請求 $res = $client ->request( 'get' , $url ); //返回狀態碼 echo $res ->getstatuscode(); //連貫操作 //$res = $client->request('get', $url)->getbody()->getcontents(); ?> |
【post請求】
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<?php require './vendor/autoload.php' ; //實例化客戶端 $client = new guzzlehttp\client(); //構造url $url = 'https://www.baidu.com' ; //post請求 $res = $client ->request( 'post' , $url , [ 'form_params' => [ 'name' => 'lws' , 'sex' => 'nan' ] ]); //返回狀態碼 echo $res ->getstatuscode(); ?> |
【post文件上傳】
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<?php require './vendor/autoload.php' ; //實例化客戶端 $client = new guzzlehttp\client(); //構造url $url = 'https://www.baidu.com' ; //post請求 $res = $client ->request( 'post' , $url , [ 'multipart' => [ [ 'name' => 'name' , 'contents' => 'lws' ], [ 'name' => 'sex' , 'contents' => 'nan' ], [ 'name' => 'tupian' , 'contents' => file_get_contents ( '1.jpg' ), 'filename' => 'lws.jpg' ] ] ]); //返回狀態碼 echo $res ->getstatuscode(); ?> |
【設置代理ip】
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?php require './vendor/autoload.php' ; //實例化客戶端 $client = new guzzlehttp\client(); //構造url $url = 'https://www.baidu.com' ; //設置代理請求 $res = $client ->request( 'get' , $url , [ 'proxy' => '111.22.33.44:6666' ]); //返回狀態碼 echo $res ->getstatuscode(); ?> |
【模擬請求頭】
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php require './vendor/autoload.php' ; //實例化客戶端 $client = new guzzlehttp\client([ 'headers' =>[ 'referer' => 'https://www.baidu,com' ]]); //構造url $url = 'https://www.baidu.com' ; //設置代理請求 $res = $client ->request( 'get' , $url ); //返回狀態碼 echo $res ->getstatuscode(); ?> |
【記錄cookie】
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php require './vendor/autoload.php' ; //實例化客戶端 $client = new guzzlehttp\client([ 'cookie' =>true]); //構造url $url = 'https://www.baidu.com' ; //設置代理請求 $res = $client ->request( 'get' , $url ); //返回狀態碼 echo $res ->getstatuscode(); ?> |
希望本文所述對大家PHP程序設計有所幫助。
原文鏈接:https://blog.csdn.net/msllws/article/details/83862462