3
$\begingroup$

This question already has an answer here:

I'm puzzled by the syntax of building a URL with HTTPRequest. I can build a URL POST request with postman and that works perfectly. The HTTP code that is build with Postman is:

POST /rest/login-sessions HTTP/1.1

Host: myhost Accept: application/json

X-API-Version: 200

Content-Type: application/json

Cache-Control: no-cache

Postman-Token: 0408e579-7571-fd08-fa7c-4bf16ea70a3d

{

"userName":"administrator",

"password":"xxx"

}

With Mathematica 11.1.1.0 on Windows 10 I try:

header = "Headers" -> {"Accept" -> "application/json", 
   "X-API-Version" -> "200", "Content-Type" -> "application/json"}
body = "Body" -> {"userName" -> "administrator", 
   "password" -> "xxx"}

gettoken = 
 HTTPRequest[
  "https://myhost/rest/login-sessions", <|Method -> "POST",
   header, body|>, VerifySecurityCertificates -> False]

With URLRead I get

URLRead[gettoken]["Body"]

Output:

"{\"errorSource\":null,\"nestedErrors\":[],\"details\":\"The JSON \ sent in the request is malformed and cannot be parsed. There is an \ error on line 1 near column 0.\",\"recommendedActions\":[\"Correct \ the malformed JSON and try the request \ again.\"],\"data\":{},\"errorCode\":\"MALFORMED_JSON\",\"message\":\"\ Malformed JSON cannot be parsed.\"}"

So it seems that the JSON format is wrong but I can't find a way to see how it's build. When I use the token generated through Postman I can build valid GET requests so that works perfectly fine.

Any thoughts?

$\endgroup$

marked as duplicate by Kuba May 15 '17 at 20:42

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ You need to ExportString the body to Json. $\endgroup$ – Kuba May 15 '17 at 20:23
  • $\begingroup$ See mathematica.stackexchange.com/questions/144405/… $\endgroup$ – Kuba May 15 '17 at 20:27
  • $\begingroup$ @Kuba, I wish I posted this question before :). Thanks! I don't find this obvious reading through the documentation. $\endgroup$ – Lou May 15 '17 at 20:37
  • $\begingroup$ I'm glad it works. I have marked it a duplicate because both are in essence about correct http request syntax. Let me know if you disagree. $\endgroup$ – Kuba May 15 '17 at 20:45
  • $\begingroup$ @Kuba No problem. I did already see that post but even then it didn't sink in :).. $\endgroup$ – Lou May 16 '17 at 20:49
2
$\begingroup$
"Body" -> 
 ExportString[<|"userName" -> "administrator", 
   "password" -> "xxx"|>, "JSON"]

Thanks to Kuba!

$\endgroup$

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