Al: How to associate an HttpHeaders collection with a WebRequest

Created on 28 Aug 2017  路  1Comment  路  Source: microsoft/AL

What's the correct way to populate an HttpHeaders collection and then use it with a WebRequest? I see methods to get the headers, to get default headers, but nothing to set the headers. Also, can you set the UserAgent and Content-Type through the HttpHeaders? Some interfaces don't allow that and they need to be set through properties. We need to be able to add custom headers, set Content-Type and UserAgent, and read the headers coming back in the response.

question

Most helpful comment

Use the GetHeaders method on the HttpRequestMessage. Then on the returned object, call the Add method. No need to write back the Headers object, you don't get a copy of the headers, but a reference.

For example, Headers.Add('User-Agent','MyAgentString') should work.
For Content-Type header, you have to work with the HttpContent object. This object has also a GetHeaders method that you can call. Then call Add on the return object, like RequestHeaders.Add('Content-Type','application/x-www-form-urlencoded').

For a complete example you may want to look at this blog post: http://www.kauffmann.nl/2017/07/18/al-web-service-examples/

>All comments

Use the GetHeaders method on the HttpRequestMessage. Then on the returned object, call the Add method. No need to write back the Headers object, you don't get a copy of the headers, but a reference.

For example, Headers.Add('User-Agent','MyAgentString') should work.
For Content-Type header, you have to work with the HttpContent object. This object has also a GetHeaders method that you can call. Then call Add on the return object, like RequestHeaders.Add('Content-Type','application/x-www-form-urlencoded').

For a complete example you may want to look at this blog post: http://www.kauffmann.nl/2017/07/18/al-web-service-examples/

Was this page helpful?
0 / 5 - 0 ratings