Set body for POST request

mysamza
Member Posts: 66
Hello mibuso community,
I am trying to send a post request (no authorization required, not even simple user name and password).
I need to send JSON data in the body, so I am trying to put the JSON content into a Text variable and trying to pass it to the HTTPClient.POST method (in its 2nd parameter).
When in AL (Visual Studio) editor I paste my JSON content between the single quotation I get an error (red line beneath by entire JSON text).
I tried searching for an example as to how to set body content before sending a POST request in AL C/AL and could not find anything on the internet.
Thank you for helping out.
I am trying to send a post request (no authorization required, not even simple user name and password).
I need to send JSON data in the body, so I am trying to put the JSON content into a Text variable and trying to pass it to the HTTPClient.POST method (in its 2nd parameter).
When in AL (Visual Studio) editor I paste my JSON content between the single quotation I get an error (red line beneath by entire JSON text).
.. Var MyContent: Text; Begin .. .. MyContent:= '{ "subject": "Something Here", "expiresIn": "15m", "private_key": "-----BEGIN PRIVATE KEY-----Something Here-----END PRIVATE KEY-----", "issuer": "Something Here" }' .. HTTPClient.POST(..,MyContent,..)
I tried searching for an example as to how to set body content before sending a POST request in AL C/AL and could not find anything on the internet.
Thank you for helping out.
0
Best Answer
-
It's actually quite simple.
JSON is nothing more than text, so the way you are attempting it without JsonObject variable is doable.
The reason you're getting a red underline is because AL C/AL doesn't know how many lines your text is.
Each line must be on it's own, between single quotes, and you can then add it to the next line. See below.MyContent:= '{' + '"subject": "Something Here",' + '"expiresIn": "15m",' + '"private_key": "-----BEGIN PRIVATE KEY-----Something Here-----END PRIVATE KEY-----",' + '"issuer": "Something Here"' + }'
However, Json doesn't need to be perfect with new lines and white spaces.
Below some examples with their output. Any of those should work to create Json for you to send in body.
You see that the first example has the same output as the last one, which uses JsonObject.
But I would still recommend using JsonObject variable since it's a more proper approach.
It also allows you to create more complex Json far easier and more dynamic.
And I think it makes your code more readable, which is great if you have to change something 6 months later.
2
Answers
-
Good morning,
If you are in AL, you can use json type objects, makes life easier for json, example:vJsonAttrs: JsonObject; vJsonAttrs2: JsonObject; vJsonAttrs3: JsonObject; vJsonAttrs4: JsonObject; vJsonValue: JsonValue; vJsonArray: JsonArray; //I will remove some pieces of the code below sicne it has some references I dont want to show vFieldRef := vRecordRef.Field(1); //Vendor No. vFieldRef2 := vRecordRef.Field(2); //Vendor Name if (format(vFieldRef.Value) <> '') and (format(vFieldRef2.Value) <> '') then begin T50010.Reset(); T50010.SetRange("Vendor No.", format(vFieldRef.Value)); if T50010.FindSet() then begin vTextvalue1 := T50010.Code; //remove: empty spaces at the end, "/", "," //this is a function I created to remove special chars that cause errors vTextvalue2 := T50010.Name; RemoveIllegalChar(vTextvalue2); vTextvalue3 := 'Title'; end else begin vTextvalue1 := 'NotFound'; vTextvalue2 := 'NotFound'; vTextvalue3 := 'Title'; end; vJsonObject.Add('datalists', vJsonAttrs); vJsonArray.Add(vJsonAttrs2); vJsonAttrs2.Add('attributes', vJsonAttrs3); vJsonAttrs3.Add('cm:name', vTextvalue2); vJsonAttrs3.Add('cm:title', vTextvalue3); vJsonObject.Add('type', 'bcpg:supplier'); vJsonObject.Add('attributes', vJsonAttrs4); //remove: empty spaces at the end, "/", "," vTextvalue1 := Format(vFieldRef2.Value); RemoveIllegalChar(vTextvalue1); vJsonAttrs4.Add('cm:name', vTextvalue1); vJsonObject.WriteTo(vpayload);
then, I add to payload (text variable):
vPayLoad := '{ "entity":' + vPayLoad + '}';
To solve your issue with single quotations, I suggest you try client.Put(RequestURL, RequestContent, ResponseMessage) as I do below.CallService('DummyprojectName',pWSURL + 'format=json', 1, vPayLoad, yoursername,yourpassword); procedure CallService(ProjectName: Text; RequestUrl: Text; RequestType: Integer; payload: Text; Username: Text; Password: Text): Text var Client: HttpClient; RequestHeaders: HttpHeaders; RequestContent: HttpContent; ResponseMessage: HttpResponseMessage; RequestMessage: HttpRequestMessage; ResponseText: Text; contentHeaders: HttpHeaders; begin RequestHeaders := Client.DefaultRequestHeaders(); RequestHeaders.Add('Authorization', CreateBasicAuthHeader(Username, Password)); case RequestType of 0: Client.Get(RequestURL, ResponseMessage); 1: begin RequestContent.WriteFrom(payload); RequestContent.GetHeaders(contentHeaders); contentHeaders.Clear(); contentHeaders.Add('Content-Type', 'application/json'); RequestMessage.Content := RequestContent; RequestMessage.SetRequestUri(RequestURL); // RequestMessage.Method := 'PATCH'; RequestMessage.Method := 'PUT'; client.Put(RequestURL, RequestContent, ResponseMessage); end; 2: begin RequestContent.WriteFrom(payload); RequestContent.GetHeaders(contentHeaders); contentHeaders.Clear(); contentHeaders.Add('Content-Type', 'application/json'); Client.Post(RequestURL, RequestContent, ResponseMessage); end; 3: Client.Delete(RequestURL, ResponseMessage); end; ResponseMessage.Content().ReadAs(ResponseText); if ResponseMessage.HttpStatusCode <> 200 then begin if StrPos(ResponseText, '"message"') <> 0 then ResponseText := CopyStr(ResponseText, StrPos(ResponseText, '"message"') + 10, StrLen(ResponseText)); /*if GuiAllowed then Error(strsubstno(Text50004, ResponseMessage.HttpStatusCode, ResponseText, payload)) else begin LogErrors(ResponseText); end; */ Error(strsubstno(Text50004, ResponseMessage.HttpStatusCode, ResponseText, payload)); end else exit(ResponseText); end;
1 -
It's actually quite simple.
JSON is nothing more than text, so the way you are attempting it without JsonObject variable is doable.
The reason you're getting a red underline is because AL C/AL doesn't know how many lines your text is.
Each line must be on it's own, between single quotes, and you can then add it to the next line. See below.MyContent:= '{' + '"subject": "Something Here",' + '"expiresIn": "15m",' + '"private_key": "-----BEGIN PRIVATE KEY-----Something Here-----END PRIVATE KEY-----",' + '"issuer": "Something Here"' + }'
However, Json doesn't need to be perfect with new lines and white spaces.
Below some examples with their output. Any of those should work to create Json for you to send in body.
You see that the first example has the same output as the last one, which uses JsonObject.
But I would still recommend using JsonObject variable since it's a more proper approach.
It also allows you to create more complex Json far easier and more dynamic.
And I think it makes your code more readable, which is great if you have to change something 6 months later.
2
Categories
- All Categories
- 73 General
- 73 Announcements
- 66.6K Microsoft Dynamics NAV
- 18.7K NAV Three Tier
- 38.4K NAV/Navision Classic Client
- 3.6K Navision Attain
- 2.4K Navision Financials
- 116 Navision DOS
- 851 Navision e-Commerce
- 1K NAV Tips & Tricks
- 772 NAV Dutch speaking only
- 617 NAV Courses, Exams & Certification
- 2K Microsoft Dynamics-Other
- 1.5K Dynamics AX
- 320 Dynamics CRM
- 111 Dynamics GP
- 10 Dynamics SL
- 1.5K Other
- 990 SQL General
- 383 SQL Performance
- 34 SQL Tips & Tricks
- 35 Design Patterns (General & Best Practices)
- 1 Architectural Patterns
- 10 Design Patterns
- 5 Implementation Patterns
- 53 3rd Party Products, Services & Events
- 1.6K General
- 1.1K General Chat
- 1.6K Website
- 83 Testing
- 1.2K Download section
- 23 How Tos section
- 252 Feedback
- 12 NAV TechDays 2013 Sessions
- 13 NAV TechDays 2012 Sessions