【发布时间】:2015-12-14 00:06:11
【问题描述】:
对于我所做的一些自动化测试,我必须记录来自 Chrome 的请求,然后在 curl 命令中重复它们。 我开始检查如何做......
【问题讨论】:
标签: php google-chrome httprequest har
对于我所做的一些自动化测试,我必须记录来自 Chrome 的请求,然后在 curl 命令中重复它们。 我开始检查如何做......
【问题讨论】:
标签: php google-chrome httprequest har
我的做法是:
脚本:
<?php
$contents=file_get_contents('/home/elyashivl/har.har');
$json = json_decode($contents);
$entries = $json->log->entries;
foreach ($entries as $entry) {
$req = $entry->request;
$curl = 'curl -X '.$req->method;
foreach($req->headers as $header) {
$curl .= " -H '$header->name: $header->value'";
}
if (property_exists($req, 'postData')) {
# Json encode to convert newline to literal '\n'
$data = json_encode((string)$req->postData->text);
$curl .= " -d '$data'";
}
$curl .= " '$req->url'";
echo $curl."\n";
}
【讨论】:
在 ElyashivLavi 的代码的基础上,我添加了一个文件名参数、读取文件时的错误检查、将 curl 置于详细模式,并禁用 Accept-encoding 请求标头,这通常会导致返回压缩输出使其难以调试,以及 curl 命令的自动执行:
<?php
function bail($msg)
{
fprintf(STDERR, "Fatal error: $msg\n");
exit(1);
}
global $argv;
if (count($argv) < 2)
bail("Missing HAR file name");
$fname = $argv[1];
$contents=file_get_contents($fname);
if ($contents === false)
bail("Could not read file $fname");
$json = json_decode($contents);
$entries = $json->log->entries;
foreach ($entries as $entry)
{
$req = $entry->request;
$curl = 'curl --verbose -X '.$req->method;
foreach($req->headers as $header)
{
if (strtolower($header->name) === "accept-encoding")
continue; // avoid gzip response
$curl .= " -H '$header->name: $header->value'";
}
if (property_exists($req, 'postData'))
{
# Json encode to convert newline to literal '\n'
$data = json_encode((string)$req->postData->text);
$curl .= " -d '$data'";
}
$curl .= " '$req->url'";
echo $curl."\n";
system($curl);
}
【讨论】: