Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

c# - 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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...