应用场景:
将PHPcurl请求代码转换成Linux可执行的curl命令,可返回连接时间与响应时间。
实现过程:
<?php
function convertToCurl($method, $url, $data = null, $headers = array()) {
$command = 'curl -w "\ntime_connect: %{time_connect}\ntime_starttransfer: %{time_starttransfer}\ntime_total: %{time_total}\n" -X ' . $method;
// 添加 URL
$command .= ' \'' . $url . '\'';
// 添加请求头
foreach ($headers as $header) {
$command .= ' -H \'' . $header . '\'';
}
// 添加请求数据
if (!empty($data)) {
if ($method === 'POST') {
// 根据 Content-Type 头部选择适当的处理方式
$contentType = '';
foreach ($headers as $header) {
if (strpos($header, 'Content-Type') !== false) {
$contentType = $header;
break;
}
}
if (strpos($contentType, 'application/json') !== false) {
// Content-Type 为 application/json,将请求数据转换为 JSON 格式
$postData = json_encode($data);
$command .= ' -d \'' . $postData . '\'';
} else {
// 其他类型的 Content-Type,将数组转换为查询字符串
$postData = http_build_query($data);
$command .= ' --data \'' . $postData . '\'';
}
} else {
// GET 请求时将数据作为查询字符串拼接到 URL
$query = http_build_query($data);
$command .= ' \'' . $url . '?' . $query . '\'';
}
}
return $command;
}
$method = 'POST';
$url = 'http://192.168.0.125/api/hsm/sym/symEncryptInternalForKEK';
$postData = [
'keyIndex' => 1,
"iv" => '22222222222222222222',
"plainData" => '111111111111111'
];
$json_data = json_encode($postData);
$headers = array(
"Content-Type: application/json; charset=utf-8",
"Content-Length:".strlen($json_data)
);
$curlCommand = convertToCurl($method, $url, $postData, $headers);
echo $curlCommand;