我尝试使用Guzzle 6(最新版本)将数据发布为Async
$client = new Client();
$request = $client->postAsync($url, [
'json' => [
'company_name' => 'update Name'
],
]);
但是我没有得到任何形式的Guzzle请求,比如终端上的帖子请求
答案 0 :(得分:4)
您是否尝试过发送请求?
http://guzzle.readthedocs.org/en/latest/index.html?highlight=async
$client = new Client();
$request = new Request('POST', $url, [
"json" => [
'company_name' => 'update Name']
]);
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
答案 1 :(得分:1)
您很可能需要致电wait();
$request->wait();
答案 2 :(得分:1)
因为它是promise,
,所以您需要输入then
除非您输入$promise->wait()
这是一个根据您的问题使用postAsync
的简单发帖请求:
$client = new Client();
$promise = $client->postAsync($url, [
'json' => [
'company_name' => 'update Name'
],
])->then(
function (ResponseInterface $res){
$response = json_decode($res->getBody()->getContents());
return $response;
},
function (RequestException $e) {
$response = [];
$response->data = $e->getMessage();
return $response;
}
);
$response = $promise->wait();
echo json_encode($response);
答案 3 :(得分:0)
Guzzle 6几乎没有实际示例/文档可供开发人员参考。我正在分享一个有关如何使用postAsync和Pool对象的示例。这允许使用guzzle 6进行并发异步请求。(我找不到直接的示例,花了2天的时间来获取工作代码)
function postInBulk($inputs)
{
$client = new Client([
'base_uri' => 'https://a.b.com'
]);
$headers = [
'Authorization' => 'Bearer token_from_directus_user'
];
$requests = function ($a) use ($client, $headers) {
for ($i = 0; $i < count($a); $i++) {
yield function() use ($client, $headers) {
return $client->postAsync('https://a.com/project/items/collection', [
'headers' => $headers,
'json' => [
"snippet" => "snippet",
"rank" => "1",
"status" => "published"
]
]);
};
}
};
$pool = new Pool($client, $requests($inputs),[
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) {
// this is delivered each successful response
},
'rejected' => function (RequestException $reason, $index) {
// this is delivered each failed request
},
]);
$pool->promise()->wait();
}