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.
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/
Most helpful comment
Use the
GetHeadersmethod on theHttpRequestMessage. Then on the returned object, call theAddmethod. 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
HttpContentobject. This object has also a GetHeaders method that you can call. Then call Add on the return object, likeRequestHeaders.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/