C# 實現對微博短網址的重定向還原

    新浪微博中,爲了節省輸入字數,經過短網址對發佈微博中連接進行重定向。咱們能夠經過代碼實現對短網址進行還原,代碼以下:ide

        private string GetOrignalLink(string link)
        {
            using (WebClient client = new MyWebClient())
            {
                client.Headers.Add("Referer", link);
                Stream stream = null;
                try
                {
                    stream = client.OpenRead(link);
                    return client.ResponseHeaders["Location"];
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    if (stream != null) stream.Close();
                }
            }
        }

        internal class MyWebClient : WebClient
        {
            protected override WebRequest GetWebRequest(Uri address)
            {
                HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
                request.AllowAutoRedirect = false;
                return request;
            }
        }
相關文章
相關標籤/搜索