GuzzleHttp示例
- 一般请求
$httpClient = new Client([
'timeout' => 5
]);
$request = $httpClient->post("http://localhost:6000", [
//body内容
//'body' => json_encode(['name' => '测试']),
//表单内容
'form_params' => [
'foo' => 'bar',
'baz' => ['hi', 'there!']
],//foo=bar&baz[0]=hi&baz[1]=there!
'headers' => [
'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36',
'Content-type' => 'application/x-www-form-urlencoded',
]
]);
echo $request->getBody()->getContents();
- 带cookie的请求 [1]
$client = new \GuzzleHttp\Client(['timeout' => 5]);
$jar = new \GuzzleHttp\Cookie\CookieJar();
$jar = \GuzzleHttp\Cookie\CookieJar::fromArray(
[
'some_cookie' => 'foo',
'other_cookie' => 'barbaz1234'
],
'localhost'
);
$jar = new \GuzzleHttp\Cookie\FileCookieJar("/tmp/test.txt");
$url = 'http://localhost:6000/';
$request = $client->request('GET', $url, [
'cookies' => $jar
]);
//遍历cookie
$it = $jar->getIterator();
while ($it->valid()) {
var_dump($it->current());
$it->next();
}
echo $request->getBody()->getContents();
//通过名字取cookie
//$cookie = $jar->getCookieByName('some_cookie');
//
//$cookie->getValue(); // 'foo'
//$cookie->getDomain(); // 'example.org'
//$cookie->getExpires(); // expiration date as a Unix timestamp
posted on 2022-07-26 18:15 dream_bccb 阅读(228) 评论(0) 编辑 收藏 举报