Reputation: 1534
I thought that HttpClient
should be able to handle 301
error code, and redirect to the correct address. However with the following address (https://www.npr.org/templates/rss/podcast.php?id=510298), it throws exception. The browsers are able to handle it properly though. Just like to understand if there is a way out or am I missing something.
HttpClient client = new HttpClient();
var s = await client
.GetStringAsync("https://www.npr.org/templates/rss/podcast.php?id=510298");
throws
Test1 [0:00.779] Failed: System.Net.Http.HttpRequestException : Response
status code does not indicate success: 301 (Moved Permanently).
System.Net.Http.HttpRequestException : Response status code does not
indicate success: 301 (Moved Permanently).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
at System.Net.Http.HttpClient.GetStringAsyncCore(Task`1 getTask)
at XUnitTestProject1.UnitTest1.Test1() in
C:\Users\res\source\repos\test\XUnitTestProject1\UnitTest1.cs:line 13
Upvotes: 4
Views: 1753
Reputation: 1534
I finally found the reason. Generally HttpClient
would handle the redirects properly, but it does not handle redirects if it is from https -> http
. Which is the case here. I was stumped by the response of the chrome browser, the displayed redirected url in chrome started with https (https://www.npr.org/rss/podcast.php?id=510298), but the actual redirect was to http://www.npr.org/rss/podcast.php?id=510298
There is an explanation at https://github.com/dotnet/runtime/issues/21446#issuecomment-298323133
Upvotes: 7