How to repeat Chrome requests as curl commands?
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
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:
<?phpfunction 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);}