Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the location from a WebClient on a HTTP 302 Redirect?

I have a URL that returns a HTTP 302 redirect, and I would like to get the URL it redirects to.

The problem is that System.Net.WebClient seems to actually follow it, which is bad. HttpWebRequest seems to do the same.

Is there a way to make a simple HTTP Request and get back the target Location without the WebClient following it?

I'm tempted to do raw socket communication as HTTP is simple enough, but the site uses HTTPS and I don't want to do the Handshaking.

At the end, I don't care which class I use, I just don't want it to follow HTTP 302 Redirects :)

like image 530
Michael Stum Avatar asked Apr 08 '10 22:04

Michael Stum


People also ask

Is HTTP 302 redirect?

What is an HTTP 302? The 302 status code is a redirection message that occurs when a resource or page you're attempting to load has been temporarily moved to a different location. It's usually caused by the web server and doesn't impact the user experience, as the redirect happens automatically.

How does a 302 redirect work?

A 302 redirect does not pass the “juice,” or keep your domain authority to its new location. It simply redirects the user to the new location for you so they don't view a broken link, a 404 not found page, or an error page.

What is HTTP 302 Object Moved?

The HyperText Transfer Protocol (HTTP) 302 Found redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the Location header.

How do you fix a 302 redirect?

How to fix it? You should only use 302 redirects where the redirection is temporary and content will come back to the original URL soon. Check the reported URLs. Where the redirection is permanent, change the redirection to 301 (Moved Permanently).


1 Answers

It's pretty easy to do

Let's assume you've created an HttpWebRequest called myRequest

// don't allow redirects, they are allowed by default so we're going to override myRequest.AllowAutoRedirect = false;  // send the request HttpWebResponse response = myRequest.GetResponse();  // check the header for a Location value if( response.Headers["Location"] == null ) {   // null means no redirect } else {   // anything non null means we got a redirect } 

Excuse any compile errors I don't have VS right in front of me, but I've used this in the past to check for redirects.

like image 77
Justin Avatar answered Oct 05 '22 15:10

Justin