14,959
edits
| Line 239: | Line 239: | ||
curl -s [URL] | curl -s [URL] | ||
</pre> | </pre> | ||
== cURL JSON Payload Issues in Windows vs Mac/Linux Systems == | |||
'''1. Problem''' | |||
Error encountered when executing the following cURL command on Windows: | |||
<pre> | |||
Invalid JSON payload received. Unknown name "": Root element must be a message. | |||
</pre> | |||
'''2. Solution''' | |||
Windows system: | |||
<pre> | |||
curl -X POST -H "Content-Type: application/json" "API_URL" -d "{\"key\":\"value\"}" | |||
</pre> | |||
Mac/Linux system: | |||
<pre> | |||
curl -X POST -H "Content-Type: application/json" "API_URL" -d '{"key":"value"}' | |||
</pre> | |||
PHP code: | |||
<pre> | |||
$is_windows = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; | |||
if ($is_windows) { | |||
$command = sprintf('-d "{\"key\":\"%s\"}"', $value); | |||
} else { | |||
$command = sprintf("-d '%s'", $json_payload); | |||
} | |||
</pre> | |||
'''3. Problem Description''' | |||
* Root cause: Windows and Mac/Linux handle quotes in shell commands differently | |||
* Windows: Requires double quotes and escaped internal quotes | |||
* Mac/Linux: Can use single quotes to wrap the complete JSON string | |||
* When using incorrect quote formatting, the JSON payload is parsed incorrectly, causing the API to return a format error message | |||
== Further reading == | == Further reading == | ||