Laravel ——GuzzleHttp 使用方法(自用)
程序员文章站
2022-04-09 20:27:09
...
Guzzle
Guzzle 是一个 PHP HTTP 客户端,致力于让发送 HTTP 请求以及与 Web 服务进行交互变得简单。
Github:https://github.com/guzzle/guzzle
Composer:https://packagist.org/packages/guzzlehttp/guzzle
发送请求
use GuzzleHttp\Client;
$client = new Client([
//跟域名
'base_uri' => 'http://localhost/test',
// 超时
'timeout' => 2.0,
]);
$response = $client->get('/get'); //http://localhost/get
$response = $client->delete('delete'); //http://localhost/get/delete
$response = $client->head('http://localhost/get');
$response = $client->options('http://localhost/get');
$response = $client->patch('http://localhost/patch');
$response = $client->post('http://localhost/post');
$response = $client->put('http://localhost/put');
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
POST
$response = $client->request('POST', 'http://localhost/post', [
'form_params' => [
'username' => 'webben',
'password' => '123456',
'multiple' => [
'row1' => 'hello'
]
]
]);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
响应
# 状态码
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK
# header
// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
echo "It exists";
}
// Get a header from the response.
echo $response->getHeader('Content-Length');
// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "\r\n";
}
# 响应体
$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
// Explicitly cast the body to a string
$stringBody = (string) $body;
// Read 10 bytes from the body
$tenBytes = $body->read(10);
// Read the remaining contents of the body as a string
$remainingBytes = $body->getContents();
- 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
自定义header
// Set various headers on a request
$client->request('GET', '/get', [
//header
'headers' => [
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
'X-Foo' => ['Bar', 'Baz']
],
//下载
'save_to'=> $filename,
//referer
'allow_redirects' => [
'referer' => '',
],
]);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
cookie 访问
$client = new \GuzzleHttp\Client();
$url = 'https://www.baidu.com/getUserInfo';
$jar = new \GuzzleHttp\Cookie\CookieJar();
$cookie_domain = 'www.baidu.com';
$cookies = [
'BAIDUID' => '221563C227ADC44DD942FD9E6D577EF2CD',
];
$cookieJar = $jar->fromArray($cookies, $cookie_domain);
$res = $client->request('GET', $url, [
'cookies' => $cookieJar,
// 'debug' => true,
]);
$body = $res->getBody();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
手册地址:http://docs.guzzlephp.org/en/stable/request-options.html#headers