WebClient或WebRequest以获取目标网页的重定向URL

时间:2018-12-07 10:03:53

标签: vb.net winforms proxy webclient webrequest

从我从Bing's Pic of the Day解析的字符串中,我下载了图片的信息,假设今天是/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567,那么我们将获得图片的完整URL,就像{{ 1}}

通常Bing的图像分辨率较高,因此我也将下载1920x1200图像。更改为http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1366x768.jpg这样的URL很容易,然后将任务交给http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg这样的WebClient

这里的问题是,有些日子分辨率1920x1200不可用,并且此分辨率(1920x1200)的下载URL将被重定向到图像的URL client1.DownloadFile(url, fileName) -默认(可以检查)。

所以我的尝试是从输入URL获取返回/重定向URL的函数:

/sa/simg/hpb/NorthMale_EN-US8782628354_1920x1200.jpg

并与输入URL进行比较以查看它们是否不同,但结果与预期不符。

任何人都可以让我知道检查此重定向URL的方法,例如按Enter键并等待网站加载后的返回URL。

请给我一个克服这一障碍的想法。谢谢!

注释: 与不同PC上的访问权限相关的某些问题使我不使用 Public Function GetWebPageURL(ByVal url As String) As String Dim Request As WebRequest = WebRequest.Create(url) Request.Credentials = CredentialCache.DefaultCredentials Return Request.RequestUri.ToString End Function ,所以我更喜欢不使用HttpWebRequest的解决方案({{ 1}}或其他更好)。


在@IvanValadares @AlenGenzić的帮助下,以及@Jimi对HttpWebRequest的{​​{1}}的建议,我来到了公平的解决方案,如下代码:

WebClient

2 个答案:

答案 0 :(得分:1)

使用AllowAutoRedirect并检查StatusCode。

var webRequest = (HttpWebRequest)System.Net.WebRequest.Create("http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg");
    webRequest.AllowAutoRedirect = false;
    using (var response = (HttpWebResponse)webRequest.GetResponse())
    {
       if (response.StatusCode == HttpStatusCode.Found)
       {
          // Have been redirect
       }
       else if (response.StatusCode == HttpStatusCode.OK)
       {
          // Have not been redirect
       }
    }

使用HttpClient

 var handler = new HttpClientHandler()
 {
    AllowAutoRedirect = false
 };
 HttpClient client = new HttpClient(handler);
 HttpResponseMessage response = await client.GetAsync("http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg");
 if (response.StatusCode == HttpStatusCode.Found)
 {
     // Have been redirect
 }
 else if (response.StatusCode == HttpStatusCode.OK)
 {
     // Have not been redirect
 }

答案 1 :(得分:1)

在@IvanValadares @AlenGenzić的帮助下,以及@Jimi对Proxy的{​​{1}}的建议,我得出了以下公平解决方案:

HttpWebRequest

不再抛出 url1 = "http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg" Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(url1), HttpWebRequest) myHttpWebRequest.MaximumAutomaticRedirections = 1 myHttpWebRequest.AllowAutoRedirect = True Dim defaultProxy As IWebProxy = WebRequest.DefaultWebProxy If (defaultProxy IsNot Nothing) Then defaultProxy.Credentials = CredentialCache.DefaultCredentials myHttpWebRequest.Proxy = defaultProxy End If Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse, HttpWebResponse) url2 = myHttpWebResponse.ResponseUri.ToString Label1.Text = url1 Label2.Text = url2