5
$\begingroup$

Is there any documentation anywhere on how to convert an invocation of curl into the Mathematica equivalent (using for example URLExecute or URLRead with HTTPRequest)?

The specific curl code I am having trouble converting to a Mathematica equivalent is

curl -X POST --data 'Expected RESPONSE.' "https://postman-echo.com/post"

where I use the example API from this service. My attempt to convert this was

URLExecute[HTTPRequest["https://postman-echo.com/post",
<|Method -> "POST", "ContentType" -> "application/x-www-form-urlencoded", 
"Body" -> ExportString[{"Expected RESPONSE." -> ""}, "JSON"]|>]]

but I did not get the results consistent with what is produced by curl. What would be the right way to use Mathematica functions for this example? I know I can just use RunProcess with curl if need be, but I want to assume I cannot or will not be able to use curl itself (e.g. on a Windows computer where I cannot install curl).

Either answers to my general or specific inquiry would be appreciated.

$\endgroup$
  • $\begingroup$ This appears to give the same result as curl on my machine. Can you elaborate on what is inconsistent? $\endgroup$ – Carl Lange Aug 27 at 10:04
11
$\begingroup$

You can use a program like Fiddler to compare the requests being generated by both:

Your call to curl generates a request like this:

POST https://postman-echo.com/post HTTP/1.1
Host: postman-echo.com
User-Agent: curl/7.65.0
Accept: */*
Connection: Keep-Alive
Content-Length: 18
Content-Type: application/x-www-form-urlencoded

Expected RESPONSE.

Your WL code generates a request like this:

POST https://postman-echo.com/post HTTP/1.1
Host: postman-echo.com
Accept: */*
Accept-Encoding: deflate, gzip
Connection: Keep-Alive
Content-Type: application/x-www-form-urlencoded
User-Agent: Wolfram HTTPClient 12.
Connection: keep-alive
Content-Length: 28

{
    "Expected RESPONSE.":""
}

As you can see, you are not sending JSON from curl, but you are from Mathematica. So you just need to get rid of the ExportString:

URLExecute[HTTPRequest["https://postman-echo.com/post",
<|Method -> "POST", "ContentType" -> "application/x-www-form-urlencoded", 
"Body" -> "Expected RESPONSE."|>]]

And the request will now be similar:

POST https://postman-echo.com/post HTTP/1.1
Host: postman-echo.com/pos
Accept: */*
Accept-Encoding: deflate, gzip
Connection: Keep-Alive
Content-Type: application/x-www-form-urlencoded
User-Agent: Wolfram HTTPClient 12.
Connection: keep-alive
Content-Length: 18

Expected RESPONSE.
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.