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()
0

4 Answers 4

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.

1
  • 1
    This just saved me from hours of pain and suffering! Thanks a lot! :D
    – Maritim
    May 17, 2013 at 22:19
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"

3
  • This is incorrect. The MSDN documentation 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, 2014 at 13:30
  • In some cases you need to set this to "false" if you have that error showing up.
    – fgalarraga
    Apr 15, 2015 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, 2016 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()
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.