首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用HttpClient,我如何阻止自动重定向,并在301的情况下获得原始状态码和forwading Url

使用HttpClient,我如何阻止自动重定向,并在301的情况下获得原始状态码和forwading Url
EN

Stack Overflow用户
提问于 2013-02-06 22:55:07
回答 1查看 28.2K关注 0票数 41

我有以下方法,它返回给定UrlHttp status code

代码语言:javascript
复制
public static async void makeRequest(int row, string url)
{
    string result;
    Stopwatch sw = new Stopwatch(); sw.Start();

    try
    {
        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage response = new HttpResponseMessage();
            response = await client.GetAsync(url);

            // dump contents of header
            Console.WriteLine(response.Headers.ToString());

            if (response.IsSuccessStatusCode)
            {
                result = ((int)response.StatusCode).ToString();
            }
            else
            {
                result = ((int)response.StatusCode).ToString();
            }
        }
    }
    catch (HttpRequestException hre)
    {
        result = "Server unreachable";
    }

    sw.Stop();
    long time = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));

    requestComplete(row, url, result, time);
}

它适用于200/404等,但是在301代码的情况下,我认为返回的结果是已经重定向(200)的结果,而不是应该返回的实际301,并且它应该有一个包含重定向指向的头部。

我在其他的.Net web请求类中也看到过类似的东西,以及将某种allowAutoRedirect属性设置为false的技术。如果这是正确的,谁能告诉我HttpClient类的正确替代方案?

This post has info on the above allowAutoRedirect concept I mean

否则,对于我知道是真正的301s的Urls,我如何让此方法返回301s而不是200s

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-06 23:16:25

我发现实现此目的的方法是创建一个HttpClientHandler实例并将其传递到HttpClient的构造函数中

代码语言:javascript
复制
public static async void makeRequest(int row, string url)
{
    string result;
    Stopwatch sw = new Stopwatch(); sw.Start();

    // added here
    HttpClientHandler httpClientHandler = new HttpClientHandler();
    httpClientHandler.AllowAutoRedirect = false;

    try
    {
        // passed in here
        using (HttpClient client = new HttpClient(httpClientHandler))
        {

        }

有关详细信息,请参阅here

票数 74
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14731980

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档