Symfony httpClient $response->getInfo() returns 空值

Symfony httpClient $response->getInfo() returns empty values

我正在尝试测量从我的应用程序调用的某些服务的响应持续时间。

我只需要一个简单的方法和一个粗略的值就足够了,我想我可以简单地使用 curl_getinfo 中的 total_time,并从 $response->getInfo() 中获取这个值,但是它始终为 0。

我缺少某些配置或 header 吗?

我用

if (!empty($headers)) {
   $httpClient = HttpClient::create(['headers' => [
          'Content-Type' => 'application/json',
          'accept' =>  'application/json',
   ]]);
} else {
   $httpClient = HttpClient::create();
}

if ($method == 'GET') {
   $response = $httpClient->request($method, $url . $pathParams);
} else {
   $response = $httpClient->request($method, $url, ['body' => json_encode($arguments)]);
}

dd($response->getInfo());

并且输出主要包含空值

^ array:44 [
  "response_headers" => []
  "http_code" => 0
  "error" => null
  "canceled" => false
  "http_method" => "POST"
  "user_data" => null
  "start_time" => 1650918719.2348
  "url" => "https://myworkingexample.com"
  "content_type" => null
  "header_size" => 0
  "request_size" => 0
  "filetime" => -1
  "ssl_verify_result" => 0
  "redirect_count" => 0
  "total_time" => 0.0
  "namelookup_time" => 0.0
  "connect_time" => 0.0
  "pretransfer_time" => 0.0
  "size_upload" => 0.0
  "size_download" => 0.0
  "speed_download" => 0.0
  "speed_upload" => 0.0
  "download_content_length" => -1.0
  "upload_content_length" => -1.0
  "starttransfer_time" => 0.0
  "redirect_time" => 0.0
  "redirect_url" => null
  "primary_ip" => ""
  "certinfo" => []
  "primary_port" => 0
  "local_ip" => ""
  "local_port" => 0
  "http_version" => 0
  "protocol" => 0
  "ssl_verifyresult" => 0
  "scheme" => ""
  "appconnect_time_us" => 0
  "connect_time_us" => 0
  "namelookup_time_us" => 0
  "pretransfer_time_us" => 0
  "redirect_time_us" => 0
  "starttransfer_time_us" => 0
  "total_time_us" => 0
  "debug" => ""
]

HttpClient 是“懒惰的”,只会在实际需要时 execute/resolve 请求。

ResponseInterface::getInfo() 的调用被定义为 non-blocking,并且不会执行该请求。它只会告诉您请求的 current 状态。如果您还没有实际执行它,returned 信息将是空的,就像您得到的那样。

对于 getInfo() 到 return 有意义的数据,您需要调用第一个“阻塞”方法。例如:

  • $response->getContent()
  • $response->getStatudCode()
  • $response->getHeaders()

其中任何一个都可能引发异常,因此您可能需要先处理该异常,然后才能调用 getInfo().