I use PowerShell to access a lot of API’s! Since a while some calls that are correct get the error: “The remote server returned an error: (401) Unauthorized.“.
In my case, this was only the case when I used Windows PowerShell (e.g., PowerShell 5.x)! PowerShell Core (7.x) worked fine.
I took me a while and a lot of Fiddler sessions to find a header in some of the requests: “Expect: 100-continue“! I found this only in calls from Windows PowerShell (e.g., PowerShell 5.x). In general, this header is a good thing! But some API providers have issues with it.
That both Invoke-WebRequest and Invoke-RestMethod have the same behaviour make sense, both use “System.Net.HttpWebRequest“, which uses the namespace “System.Net.Http.Headers“.
Here is the error that I got from several API providers:
Based on the docs that I found, the default value is true! Why ever I saw this Header in Windows PowerShell only! PowerShell Core (on any Plattform) never added this header. It is enabled by default on both.
Anyway, you can disable this header:
In my case, I just added the following to my scripts and modules:
You can check if Expect100Continue is enabled (this the default):