如何获得重定向响应

11

假设我在浏览器中输入www.abc.com,浏览器会自动重定向到www.xyz.com。我需要从服务器端获取该重定向URL。也就是说,如果www.abc.com返回一个重定向url www.xyz.com,我如何从原始URL www.abc.com 请求此重定向URL(www.xyz.com)?

1个回答

23

以下是一个网络爬虫示例,展示了如何处理重定向:

  HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
  webRequest.AllowAutoRedirect = false;  // IMPORTANT
  webRequest.UserAgent = ...;
  webRequest.Timeout = 10000;           // timeout 10s

  // Get the response ...
  using (webResponse = (HttpWebResponse)webRequest.GetResponse())
  {   
     // Now look to see if it's a redirect
     if ((int)webResponse.StatusCode >= 300 && (int)webResponse.StatusCode <= 399)
     {
       string uriString = webResponse.Headers["Location"];
       Console.WriteLine("Redirect to " + uriString ?? "NULL");
       ...
     }
  }

1
由于某些原因,我的编辑未被接受... 这样调用 Close() 是一种不好的做法,你应该使用 using - Dmitry Fedorkov
1
这对我不起作用。尽管我能够连接到资源,但我仍然得到了一个空值。 - artifex_somnia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接