Set body for POST request

mysamzamysamza 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).
..
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.

Best Answer

  • ResolusResolus Member Posts: 40
    edited 2021-11-18 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.

    6hnyiagdf4yu.png

    hndys9akgjrp.png

    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 ;).

Answers

  • txerifftxeriff Member Posts: 500
    edited 2021-11-17
    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;
    
    
  • ResolusResolus Member Posts: 40
    edited 2021-11-18 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.

    6hnyiagdf4yu.png

    hndys9akgjrp.png

    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 ;).
Sign In or Register to comment.