(自学自用,不喜勿喷,谢谢)
(问题:没办法真正的异步进行求情)
Guzzle(curl)
composer require guzzlehttp/guzzle
Guzzle 是一个 PHP HTTP 客户端,致力于让发送 HTTP 请求以及与 Web 服务进行交互变得简单。
Github:https://github.com/guzzle/guzzle
Composer:https://packagist.org/packages/guzzlehttp/guzzle
官网:https://docs.guzzlephp.org/en/stable/overview.html
发送请求
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');
POST
$response = $client->request('POST', 'http://localhost/post', [
'form_params' => [
'username' => 'webben',
'password' => '123456',
'multiple' => [
'row1' => 'hello'
]
]
]);
//传json格式参数
$response = $client->post('/xxx', [
'headers' => ['Content-Type' => 'application/json'],//设置请求头为json
'json' => [
'network_id' => 8,
'state' => 0,
'terminal_name' => ''
]
]);
$body = $response->getBody()->getContents();
响应
# 状态码
$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();
自定义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' => '',
],
]);
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();
网友评论