如何在另一个完成后发出 http 客户端请求?
How can I make a http client request after another is completed?
在我的 Symfony 函数中,我正在创建一个文件夹,并在该文件夹内创建另一个文件夹:
$client = HttpClient::create();
$createFolder = $client->request('MKCOL', $path.$foldername, [
'auth_basic' => [$user, $authKey],
]);
$createImageFolder = $client->request('MKCOL', $path.$foldername/images', [
'auth_basic' => [$user, $authKey],
]);
效果很好,但有时创建第一个文件夹的速度不够快,无法创建图像文件夹。有没有办法让第二个请求可以等到第一个文件夹创建好?
$client->request()
是异步的。您可以使用 $client->getStatusCode()
等待响应,然后再进行下一步操作。你也可以用它来确认第一次操作是否成功。
$client = HttpClient::create();
$createFolder = $client->request('MKCOL', $path.$foldername, [
'auth_basic' => [$user, $authKey],
]);
$code = $createFolder->getStatusCode();
if ($code < 300) { // Creation was successful
$createImageFolder = $client->request('MKCOL', $path.$foldername/images', [
'auth_basic' => [$user, $authKey],
]);
}
Responses are always asynchronous, so that the call to the method returns immediately instead of waiting to receive the response:
<?php
// code execution continues immediately; it doesn't wait to receive the response
$response = $client->request('GET', 'http://releases.ubuntu.com/18.04.2/ubuntu-18.04.2-desktop-amd64.iso');
// getting the response headers waits until they arrive
$contentType = $response->getHeaders()['content-type'][0];
// trying to get the response content will block the execution until
// the full response content is received
$content = $response->getContent();
因此您需要调用 $response->getContent()
(或任何其他类似 getHeaders()
)来阻止直到接收!
在我的 Symfony 函数中,我正在创建一个文件夹,并在该文件夹内创建另一个文件夹:
$client = HttpClient::create();
$createFolder = $client->request('MKCOL', $path.$foldername, [
'auth_basic' => [$user, $authKey],
]);
$createImageFolder = $client->request('MKCOL', $path.$foldername/images', [
'auth_basic' => [$user, $authKey],
]);
效果很好,但有时创建第一个文件夹的速度不够快,无法创建图像文件夹。有没有办法让第二个请求可以等到第一个文件夹创建好?
$client->request()
是异步的。您可以使用 $client->getStatusCode()
等待响应,然后再进行下一步操作。你也可以用它来确认第一次操作是否成功。
$client = HttpClient::create();
$createFolder = $client->request('MKCOL', $path.$foldername, [
'auth_basic' => [$user, $authKey],
]);
$code = $createFolder->getStatusCode();
if ($code < 300) { // Creation was successful
$createImageFolder = $client->request('MKCOL', $path.$foldername/images', [
'auth_basic' => [$user, $authKey],
]);
}
Responses are always asynchronous, so that the call to the method returns immediately instead of waiting to receive the response:
<?php
// code execution continues immediately; it doesn't wait to receive the response
$response = $client->request('GET', 'http://releases.ubuntu.com/18.04.2/ubuntu-18.04.2-desktop-amd64.iso');
// getting the response headers waits until they arrive
$contentType = $response->getHeaders()['content-type'][0];
// trying to get the response content will block the execution until
// the full response content is received
$content = $response->getContent();
因此您需要调用 $response->getContent()
(或任何其他类似 getHeaders()
)来阻止直到接收!