无法管理重定向

时间:2018-04-22 16:39:36

标签: c#

我试图管理此网站上的重定向:https://uk.soccerway.com,所以我写了这段代码:

public static string GetHtml(string url)
{
        HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);

        try
        {
            webReq.AllowAutoRedirect = false;
            HttpWebResponse response = webReq.GetResponse() as HttpWebResponse;                
            WebClient client = new WebClient();
            client.Encoding = System.Text.Encoding.UTF8;
            url = (response.Headers["Location"] != null) ? response.Headers["Location"] : url;
            return client.DownloadString(url);
        }
        catch (WebException)
        {
            throw;
        }
    }

这会返回一个异常,特别是:

  

'远程服务器返回错误:(302)暂时移动。'

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我可以看到这对许多其他用户来说是一个有用的答案,所以阅读this article帮助我到达下面的代码。如果有超过1个重定向,它会递归处理重定向。最后它返回响应:

public static HttpResponseMessage MakeRequest(string url)
{
    using (var client = new HttpClient())
    {
        var request = new HttpRequestMessage()
        {
            RequestUri = new Uri(url),
            Method = HttpMethod.Get
        };

        HttpResponseMessage response = client.SendAsync(request).Result;
        var statusCode = (int)response.StatusCode;

        // We want to handle redirects ourselves so that we can 
        // determine the final redirect Location (via header)
        if (statusCode >= 300 && statusCode <= 399)
        {
            var redirectUri = response.Headers.Location;
            if (!redirectUri.IsAbsoluteUri)
            {
                redirectUri = new Uri(request.RequestUri.
                    GetLeftPart(UriPartial.Authority) + redirectUri);
            }

            return MakeRequest(redirectUri.AbsoluteUri);
        }

        return response;
    }
}

<强>用法

HttpResponseMessage response = MakeRequest("https://uk.soccerway.com");
if (response.IsSuccessStatusCode)
{
    string content = response.Content.ReadAsStringAsync().Result;
}