Using WebClient in C# is there a way to get the URL of a site after being redirected?

后端 未结 8 1474
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 03:21

Using the WebClient class I can get the title of a website easily enough:

WebClient x = new WebClient();    
string source = x.DownloadString(s);
string titl         


        
相关标签:
8条回答
  • 2020-11-29 04:05

    In case you are only interested in the redirect URI you can use this code:

    public static string GetRedirectUrl(string url)
    {
         HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(url);
         request.AllowAutoRedirect = false;
    
         using (HttpWebResponse response = HttpWebResponse)request.GetResponse())
         {
             return response.Headers["Location"];
         }
    }
    

    The method will return

    • null - in case of no redirect
    • a relative url - in case of a redirect

    Please note: The using statement (or a final response.close()) is essential. See MSDN Library for details. Otherwise you may run out of connections or get a timeout when executing this code multiple times.

    0 讨论(0)
  • 2020-11-29 04:05

    Ok this is really hackish, but the key is to use the HttpWebRequest and then set the AllowAutoRedirect property to true.

    Here's a VERY hacked together example

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://tinyurl.com/dbysxp");
            req.Method = "GET";
            req.AllowAutoRedirect = true;
            WebResponse response = req.GetResponse();
    
            response.GetResponseStream();
            Stream responseStream = response.GetResponseStream();
    
            // Content-Length header is not trustable, but makes a good hint.
            // Responses longer than int size will throw an exception here!
            int length = (int)response.ContentLength;
    
            const int bufSizeMax = 65536; // max read buffer size conserves memory
            const int bufSizeMin = 8192;  // min size prevents numerous small reads
    
            // Use Content-Length if between bufSizeMax and bufSizeMin
            int bufSize = bufSizeMin;
            if (length > bufSize)
                bufSize = length > bufSizeMax ? bufSizeMax : length;
    
            StringBuilder sb;
            // Allocate buffer and StringBuilder for reading response
            byte[] buf = new byte[bufSize];
            sb = new StringBuilder(bufSize);
    
            // Read response stream until end
            while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
                sb.Append(Encoding.UTF8.GetString(buf, 0, length));
    
            string source = sb.ToString();string title = Regex.Match(source, 
            @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>",RegexOptions.IgnoreCase).Groups["Title"].Value;
    

    enter code here

    0 讨论(0)
提交回复
热议问题