Symfony httpClient $response->getInfo()返回空值

f0ofjuux  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(158)

我试图测量从我的应用程序调用的某些服务的响应持续时间。
我只需要一个简单的方法,一个粗略的值就足够了,我想我可以简单地从curl_getinfo使用total_time,然后从$response->getInfo()得到这个值,但它总是0。
是否有一些配置或标题,我错过了?
我用

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" => ""
]

ijnw1ujt

ijnw1ujt1#

HttpClient是“懒惰的”,并且只在实际需要时执行/解析请求。
ResponseInterface::getInfo()的调用被定义为非阻塞的,并且不会执行请求。它只会告诉你请求的 * 当前 * 状态。如果你没有实际执行它,返回的信息将是空的,就像你得到的一样。
为了让getInfo()返回有意义的数据,你需要调用第一个“阻塞”方法。例如:

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

任何一个都可能抛出异常,所以在调用getInfo()之前,您可能需要处理这个异常。

相关问题