gpt4 book ai didi

c# - 使用 HttpClient C# .NET 获取 URL

转载 作者:行者123 更新时间:2023-11-30 13:55:23 30 4
gpt4 key购买 nike

我正在尝试使用 HttpClient 获取页面的 URL。我以前只使用过 HttpWebRequest,但我需要将其设为异步方法。在下面的代码中,myUri 始终返回 null,这导致我稍后尝试处理它时抛出异常。

位置 header 是否使用错误?

        string myUrl = "http://www.example.com/"; 
Uri myUri= new Uri(myUrl);
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(myUri))
{
if (response.IsSuccessStatusCode)
{
myUri= response.Headers.Location;
Debug.WriteLine("True "+ myUri);
}
else {
Debug.WriteLine("False " + myUri);
}
}

最佳答案

这是因为 HttpClient 会自动跟随重定向。如果您需要页面重定向到的 URL,则需要阻止它自动跟随:

将您的代码更改为以下内容:

string myUrl = "http://www.example.com/"; 
Uri myUri= new Uri(myUrl);

HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.AllowAutoRedirect = false;

using (HttpClient client = new HttpClient(httpClientHandler))

关于c# - 使用 HttpClient C# .NET 获取 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35026180/

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