Spread the love

This is going to be a short post, but I ran into some difficulties calling a web service the other day, and while using the HTTP client to call web services is something that I have done a thousand times, I have always used the HttpClient.Post() however this time I could not use the HttpClient.Post() but I had to use the HttpClient.Send() because I had to send the Accept Header, which you cannot set on the HttpContent but you have to set it on the HttpRequestMessage. Another thing that I had to do which I am not accustomed to was that I had to send an Authorization header as a Bearer token, now this does not have anything to do with using the Post() or the Send() but anyhow to add an Authorization header you must do the following to your HttpClient.

Client.DefaultRequestHeaders.Add('Authorization', StrSubstNo('Bearer %1', '{{TOKEN}}'));

For some reason, I had to clear my HttpClient before I could set my header, now the complete code that I used to call the Http endpoint using send is below:

    procedure PostJsonUsingSend(Url: Text; PayLoad: text): Text
        Result: Text;
        Content: HttpContent;
        Response: HttpResponseMessage;
        Request: HttpRequestMessage;
        Client: HttpClient;
        RequestHeader: HttpHeaders;
        ContentHeader: HttpHeaders;
        //Set auth
        Client.DefaultRequestHeaders.Add('Authorization', StrSubstNo('Bearer %1', '{TOKEN}}'));
        //Request headers
        RequestHeader.Add('Accept', 'application/json');
        //Set content
        Request.Content := Content;
        //Content headers
        ContentHeader.Add('Content-Type', 'application/json');
        //Set URL and type
        //Call HTTP
        Client.Send(Request, Response);
        Content := Response.Content;

What you have to pay attention to when using Send is that you must set the Content on the HttpRequestMessage this is done with the following lines:

 //Set content
Request.Content := Content;

If you do not do this you will not send your payload and depending on the endpoint you might get back an error telling you that you are not allowed to call the endpoint with a blank payload.

And that is it for this short blog post, I hope it might help some of you not to waste the same amount of time that I did trying to get my Send() to work until next time stay safe.

Leave a Reply