【问题标题】:How to repeat Chrome requests as curl commands?如何将 Chrome 请求重复为 curl 命令?
【发布时间】:2015-12-14 00:06:11
【问题描述】:

对于我所做的一些自动化测试,我必须记录来自 Chrome 的请求,然后在 curl 命令中重复它们。 我开始检查如何做......

【问题讨论】:

标签: php google-chrome httprequest har


【解决方案1】:

我的做法是:

  1. 在开发者工具打开时访问网站。
  2. 发出请求,确保它们已登录到控制台。
  3. 右键单击请求,选择“另存为带有内容的 HAR”,然后保存到文件中。
  4. 然后运行以下php脚本解析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";
}

【讨论】:

    【解决方案2】:

    不知道他们在哪个版本中添加了此功能,但 Chrome 现在提供了“另存为 cURL”选项:

    您可以通过在开发者工具的网络选项卡下访问它,然后右键单击 XHR 请求

    【讨论】:

    • 就我而言,我必须复制许多请求,所以我不想检查每个请求并复制为 curl。所以我一直在寻找批量复制解决方案
    • 你可以全部复制为 cURL
    • 但是,就我而言,我需要运行用户收集的 HAR 文件。我本可以让他将所有内容都保存为 cURL,但我更喜欢 HAR 格式,因为它更易于解析和分析。
    【解决方案3】:

    在 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 2017-05-25
      • 2020-10-01
      • 2016-05-20
      • 2016-08-04
      相关资源
      最近更新 更多