gpt4 book ai didi

c# - HttpClient GetStringAsync 返回 301,但浏览器能够导航到正确的地址

转载 作者:行者123 更新时间:2023-12-05 02:11:21 41 4
gpt4 key购买 nike

我认为 HttpClient 应该能够处理 301 错误代码,并重定向到正确的地址。但是对于以下地址 ( https://www.npr.org/templates/rss/podcast.php?id=510298 ),它会抛出异常。不过,浏览器能够正确处理它。只是想了解是否有出路或者我错过了什么。

HttpClient client = new HttpClient();

var s = await client
.GetStringAsync("https://www.npr.org/templates/rss/podcast.php?id=510298");

抛出

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

最佳答案

我终于找到原因了。通常 HttpClient 会正确处理重定向,但如果它来自 https -> http,它不会处理重定向。这里就是这种情况。我被 chrome 浏览器的响应难住了,chrome 中显示的重定向 url 以 https (https://www.npr.org/rss/podcast.php?id=510298) 开头,但是实际重定向到 http://www.npr.org/rss/podcast.php?id=510298

https://github.com/dotnet/runtime/issues/21446#issuecomment-298323133 有解释

关于c# - HttpClient GetStringAsync 返回 301,但浏览器能够导航到正确的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57618605/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com