19

I am attempting to request a page like "http://www.google.com/?q=random" using the webrequest class in vb.net. we are behind a firewall, so we have to authenticate our requests. I have gotten past the authentication part by adding my credentials. But once that works it seems to go into a redirecting loop.

Does anyone have an ideas, comments, suggetions why this is? Has anyone else experienced this problem?

Dim loHttp As HttpWebRequest =  CType(WebRequest.Create(_url), HttpWebRequest)
loHttp.Timeout = 10000
loHttp.Method = "GET"
loHttp.KeepAlive = True
loHttp.AllowAutoRedirect = True
loHttp.PreAuthenticate = True
Dim _cred1 As NetworkCredential = ... //this is setup
//snip out this stuff
loHttp.Credentials = _cc
loWebResponse = loHttp.GetResponse()
SwissCoder
  • 2,514
  • 4
  • 28
  • 40
tooleb
  • 612
  • 3
  • 6
  • 14

4 Answers4

44

Make sure you have a cookie container setup.

CookieContainer cookieContainer = new CookieContainer();
loHttp.CookieContainer = cookieContainer;

You are probably not saving cookies and getting caught in a redirect loop.

Darryl Braaten
  • 5,229
  • 4
  • 36
  • 50
8
loHttp.AllowAutoRedirect = true

Instead of this, you have to use

loHttp.AllowAutoRedirect = False

to avoid error the error

"TOO MANY AUTOMATIC REDIRECTION WERE ATTEMPTED"

Dhivya
  • 89
  • 1
  • 1
  • This is incorrect. The [MSDN documentation](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.allowautoredirect(v=vs.110).aspx) for the `HttpWebRequest.AllowAutoRedirect` property states: "Set `AllowAutoRedirect` to *true* if you want the request to automatically follow HTTP redirection headers to the new location of the resource. The maximum number of redirections to follow is set by the `MaximumAutomaticRedirections` property." The above link is for .NET 4.5, but the docs say the same thing all the way back to 2.0. – David Sep 23 '14 at 13:30
  • In some cases you need to set this to "false" if you have that error showing up. – fgalarraga Apr 15 '15 at 18:32
  • This appears to "work" because it does not actually follow the auto redirects, it just stops on the first page. So depending on what you want to happen will determine if this answer is correct. It will **not** get you to the same location that the browser will get you to. – Jim Nov 17 '16 at 21:13
2

I translated the C# that Darryl provided to VB and inserted it before the getResponse call.

Dim cookieContainer As CookieContainer = New CookieContainer()
loHttp.CookieContainer = cookieContainer
loWebResponse = loHttp.GetResponse()
tooleb
  • 612
  • 3
  • 6
  • 14
0

Maybe, you can individually process for each redirection by catch up Location from response and use suitable cookies.