For some automated tests that I did, I had to record requests from Chrome, and then repeat them in curl commands. I start checking how to do it...
How to repeat Chrome requests as curl commands?
Asked Answered
There is another implementation at github.com/mattcg/har-to-curl –
Bridesmaid
The way I did it was:
- Access websites when the developers tools open.
- Issue requests, make sure they are logged in the console.
- Right click on the requests, select 'Save as HAR with content', and save to a file.
- Then run the following php script to parse the HAR file and output the correct curls:
script:
<?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";
}
Don't know in which version they added this feature, but Chrome now offers a "Save as cURL" option:
You can access this by going under the Network tab of the Developer Tools, and right clicking on a XHR request
In my case, I had to copy many requests, so I didn't want to go over each one and copy as curl. So I was looking for a batch copy solution –
Kassandrakassaraba
You can do Copy all as cURL –
Gymnastic
However, in my case, I needed to run an HAR file that a user has collected. I could have had him do save all as cURL, but I like the HAR format better because it is easier to parse and analyze. –
Gymnastic
Building upon the code by ElyashivLavi, I added a file name argument, error checking when reading from the file, putting curl in verbose mode, and disabling the Accept-encoding request header, which usually results in getting back compressed output that would make it hard to debug, as well as automatic execution of curl commands:
<?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);
}
© 2022 - 2024 — McMap. All rights reserved.