Uri myuri = new Uri("https://buffalousercontent.blob.core.windows.net/371-static/profileimages/full/39398");
This is my uri, when u hit means it receives image based on user some user doesn't contains image at that time it receives error page.
How to check the received one is image or something in C# code?
If you're just looking to validate that the URL contains an image:
bool ValidateImage(string url)
{
HttpWebRequest r = (HttpWebRequest)WebRequest.Create(url);
r.Method = "GET";
try
{
HttpWebResponse resp = (HttpWebResponse)r.GetResponse();
if (resp.ContentType == "image/jpeg")
{
Console.WriteLine("Image retrieved successfully.");
// Process image
return true;
}
else
{
Console.WriteLine("Unable to retrieve image");
}
}
catch
{
Console.WriteLine("Unable to retrieve image.");
}
return false;
}
Obviously, change the ContentType check to whatever makes sense for your application. You could also use HEAD as the request method (as in #Chris' answer) if you're just looking to validate the content type and not download the entire image right then.
As mentioned in the other answers, you can look at the content type of the response, or you could try to create an image from the URI.
try {
var client = new WebClient();
var image = Image.FromStream(client.OpenRead(uri));
}
catch(ArguementException e) {
// this exception will be thrown if the URI doesn't point to a valid image.
}
To check if there is an error, you have to send a request and then receive an error or a good blob.
To send a request, you can use WebClient as described here :
public bool CheckUri(Uri uri){
using(var client = new WebClient()){
try{
client.DownloadFile(uri);
return true;
}catch{//error detected
return false;
}
}
}
Do a httprequest and check if the response contenttype equals "image/". This function should do the trick!
Boolean IsImageUrl(string URL)
{
var req = (HttpWebRequest)HttpWebRequest.Create(URL);
req.Method = "HEAD";
using (var resp = req.GetResponse())
{
return resp.ContentType.ToLower(CultureInfo.InvariantCulture)
.StartsWith("image/");
}
}
Well a Uri object itself doesn't know what will happen when you use it as the address of a GET request.
To check if a string is a valid Uri, you can use
Uri uri;
bool valid = Uri.TryCreate(stringInput, UriKind.Absolute, out uri);
To check what the file type of a request is
using (var client = new HttpClient())
{
var response = client.GetAsync(uri).Result;
var contentType = response.Content.Headers.ContentType;
}
You can use the Azure client API to do this. Add a reference to Microsoft.WindowsAzure.StorageClient:
bool IsBlobJpeg(string blobUri)
{
try
{
Microsoft.WindowsAzure.StorageClient.CloudBlob blob =
new CloudBlob(
blobUri);
blob.FetchAttributes();
return (blob.Properties.ContentType == "image/jpeg");
}
catch (StorageClientException ex)
{
Console.WriteLine(String.Format("{0} Does not exist", blobUri));
return false;
}
}
Related
Is it possible to make two consecutive web requests in c#? So make the inital request and then make a request from that response. I am doing this to fill out two consecutive forms in a c# program.
string postdata = "param1=...¶m2=..."
var data1 = Encoding.ASCII.GetBytes(postdata);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data1.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data1, 0, data1.Length);
}
var response = (HttpWebResponse)request.GetResponse();
So if this is my first form how would I then go and fill out the second form that the completion of this form should lead to?
This is a (very) stripped down version of some code using HttpWebRequest that can send a request either via parameters or content but assumes either (or both) are objects passed in. E.g., if you need to send parameters like login and password usage would look like;
var response = HttpUtilities.Post("http://www.someurl.com/", new { login = "user", password = "1234");
// check response data + codes, etc...
var secondResponse = HttpUtilities.Post("http://www.someurl.com/page2", new { data = "stuff" });
The code below won't necessarily compile as I had to strip it down manually and is untested in its current form but it gives a very good idea of what's needed to check the response, debug, etc.;
namespace Helpers.Web
{
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Net.Http;
using System.Reflection;
using System.Web;
using Newtonsoft.Json;
using NLog;
public class HttpUtilities
{
#region NLog instance
/// <summary>
/// The single instance of an NLog LogManager for this class.
/// </summary>
private static Logger _logger = LogManager.GetCurrentClassLogger();
#endregion
#region Public Methods
public static TResponse Post<TResponse, TContent>(string uri, object parameters = null, TContent content = null)
where TContent : class
{
return GetResponse<TResponse, TContent>(uri, SerializeToQueryString(parameters),
content, HttpMethod.Post);
}
public static HttpWebResponse GetResponse<TContent>(string uri,
string parameters,
TContent content,
HttpMethod method)
where TContent : class
{
// build the full URL if parameters have been specified
if (!string.IsNullOrEmpty(parameters))
{
uri += "?" + parameters;
}
// make the request and send back the results
HttpWebRequest webRequest = BuildWebRequest(uri, content, method);
return GetWebResponse(uri, webRequest);
}
#endregion
#region Private Methods
private static HttpWebRequest BuildWebRequest<TContent>(string uri, TContent content, HttpMethod method)
where TContent : class
{
// get the request details
_logger.Trace("Building request for [{0}]", uri);
// set the web request details
_logger.Trace("Setting request header details...");
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = method.ToString();
webRequest.ContentType = "application/json";
webRequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
// do we have content to insert
string serializedContent = string.Empty;
if (content != null)
{
JsonSerializerSettings jsonSettings = new JsonSerializerSettings
{
// ignore the self referencing nature of EntityFramework objects and skip
// over the self references when serializing
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
// serialize the object as json and convert it into bytes we can
// inject into the content stream of the request.
serializedContent = JsonConvert.SerializeObject(content, jsonSettings);
UTF8Encoding encoding = new UTF8Encoding();
byte[] byteContent = encoding.GetBytes(serializedContent);
webRequest.ContentLength = byteContent.Length;
// write the content
// NOTE: the act of writing out the data actually sends the request!
_logger.Trace("Sending request and getting response from [{0}]", uri);
using (var contentStream = webRequest.GetRequestStream())
{
contentStream.Write(byteContent, 0, byteContent.Length);
}
_logger.Trace("Injected content into request to [{0}]. Content: {1}", uri, serializedContent);
}
else
{
// if there's no content then we haven't actually sent the request yet. However we still
// need to set the header details.
webRequest.ContentLength = 0;
_logger.Trace("Sending request and getting response from [{0}]", uri);
}
return webRequest;
}
private static HttpWebResponse GetWebResponse(string uri, HttpWebRequest webRequest)
{
HttpWebResponse response;
try
{
_logger.Debug("Sending [{0}] request to [{1}]...", webRequest.Method, webRequest.RequestUri.AbsoluteUri);
response = (HttpWebResponse)webRequest.GetResponse();
}
catch (WebException wex)
{
// we might still have response information on the request
// if this is so, then extract it and log it as we'll need to
// find out what the server actually replied with in order to debug
// what went on
_logger.Error(wex, "There was a problem getting a response from the server");
if (wex.Response != null)
{
try
{
// NOTE: this can be caused by the server returning a YSOD. You can see the formatted result
// in debug mode by using the HTML visualizer when looking at the content of the
// wResponseContent variable.
_logger.Debug("Attempting to extract server response details from WebException...");
using (Stream wResponseStream = wex.Response.GetResponseStream())
{
if (wResponseStream != null)
{
using (StreamReader wStreamReader = new StreamReader(wResponseStream))
{
string wResponseContent = wStreamReader.ReadToEnd();
_logger.Debug(wex, "Received fault response from [{0}]. Response: {1}",
uri, wResponseContent);
}
}
}
}
catch (Exception eex)
{
// there was an issue trying to get the response content from the original error.
// There's nothing more we can do except log this exception and rethrow the
// original.
_logger.Fatal(eex, "There was a problem getting response details from a WebException raised from the server");
throw;
}
}
else
{
_logger.Debug("No response data present in the exception.");
}
throw;
}
catch (Exception ex)
{
_logger.Error(ex, "There was a problem getting a response from [{0}]", uri);
throw;
}
return response;
}
private static string SerializeToQueryString(object parameters)
{
// if we weren't given anything then there's nothing we can do
if (parameters == null)
{
return string.Empty;
}
if (parameters is string)
{
return parameters as string;
}
// iterate over the parameter properties and build the query string
Type type = parameters.GetType();
BindingFlags flags = BindingFlags.Instance
| BindingFlags.GetProperty
| BindingFlags.Public;
if (type.IsInterface)
{
// if the type is an interface, only get the interface's members
flags |= BindingFlags.FlattenHierarchy;
}
PropertyInfo[] properties = type.GetProperties(flags);
List<string> urlParameters = new List<string>();
foreach (PropertyInfo prop in properties)
{
// convert the value to a string first so that we can make it safe
// to put into the URL
_logger.Trace("Getting value from {0}.{1} [{2}]", type.FullName, prop.Name, prop.PropertyType.FullName);
object rawValue = prop.GetValue(parameters, null);
string propertyValue = string.Empty;
if (rawValue != null)
{
propertyValue = rawValue.ToString();
}
urlParameters.Add(string.Format("{0}={1}", prop.Name, HttpUtility.UrlEncode(propertyValue)));
}
return string.Join("&", urlParameters.ToArray());
}
#endregion
}
}
i want check file in subdomain at another subdomain, file in sub1 and i want check this file in sub2.
address file in sub1: sub1.mysite.com/img/10.jpg and
Server.MapPath(#"~/img/10.jpg");
i have check this file in sub2, so i use this code: some code here it's
if (System.IO.File.Exists(Server.MapPath(#"~/img/10.jpg")))
{
...
}
if (System.IO.File.Exists("http://sub1.mysite.com/img/10.jpg"))
{
...
}
but its not working. please help me.
You'll have to access it via HTTP using HttpWebRequest. You could create a utility method to do this, something like:
public static bool CheckExists(string url)
{
Uri uri = new Uri(url);
if (uri.IsFile) // File is local
return System.IO.File.Exists(uri.LocalPath);
try
{
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
request.Method = "HEAD"; // No need to download the whole thing
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
return (response.StatusCode == HttpStatusCode.OK); // Return true if the file exists
}
catch
{
return false; // URL does not exist
}
}
And then call it like:
if(CheckExists("http://sub1.mysite.com/img/10.jpg"))
{
...
}
Use HttpWebRequest to send request for resource and inspect the response.
Something like:
bool fileExists = false;
try
{
HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create("http://sub1.mysite.com/img/10.jpg");
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
fileExists = (response.StatusCode == HttpStatusCode.OK);
}
}
catch
{
}
In a web application I have to first check if an image exists and then display this image or a dummy image.
I use the following code and it works for URLS like:
"http://www.somedomain.com/niceimage.png"
"https://www.somedomain.com/niceimage.png".
public virtual bool WebResourceExists(string url)
{
WebHeaderCollection headers = null;
WebResponse response = null;
try
{
WebRequest request = WebRequest.Create(url);
request.Method = "HEAD";
response = request.GetResponse();
headers = response.Headers;
bool result = int.Parse(headers["Content-Length"]) > 0;
return result;
}
catch (System.Net.WebException)
{
return false;
}
catch (Exception e)
{
_log.Error(e);
return false;
}
finally
{
if (response != null)
{
response.Close();
}
}
}
In some places the the method is called with protocol agnostic urls like "//www.somedomain.com/niceimage.png".
There is an exception thrown for such urls:
System.InvalidCastException: Unable to cast object of type
'System.Net.FileWebRequest' to type 'System.Net.HttpWebRequest'
Is there a way to use protocol agnostic urls other then just prepending "http:" to the url?
Protocol-agnostic URLs are resolved by the browser using the current protocol, and are used to avoid making HTTP requests from an HTTPS page.
Code executing on the server doesn't really have a concept of a "current protocol". Whilst ASP.NET can determine whether the current request was issued over HTTP or HTTPS, the WebRequest classes are not restricted to ASP.NET applications, so they cannot rely on this.
You will need to specify the protocol. Whether you use HTTP or HTTPS will depend on whether you're concerned about third-parties eavesdropping on the connection between your server and "www.somedomain.com".
What about a two step process, check for the http version, if it doesn't exist check for https. I've quickly hacked together a basic example of how this could work but am not able to properly test and check it so it might need some tidying up/refactoring!
public virtual bool WebResourceExists(string url)
{
WebHeaderCollection headers = null;
WebResponse response = null;
try
{
if (url.StartsWith(#"//") {
url = "http:";
}
WebRequest request = WebRequest.Create(url);
request.Method = "HEAD";
response = request.GetResponse();
headers = response.Headers;
bool result = int.Parse(headers["Content-Length"]) > 0;
return result;
}
catch (System.Net.WebException)
{
if (url.StartsWith(#"http://") {
url = url.Replace("http://","https://");
} else {
return false;
}
try {
WebRequest request = WebRequest.Create(url);
request.Method = "HEAD";
response = request.GetResponse();
headers = response.Headers;
bool result = int.Parse(headers["Content-Length"]) > 0;
return result;
}
catch (System.Net.WebException)
{
return false;
}
}
catch (Exception e)
{
_log.Error(e);
return false;
}
finally
{
if (response != null)
{
response.Close();
}
}
}
I try download file from server with FileWebRequest. But I get error:
Method on download is here:
public string HttpFileGetReq(Uri uri, int reqTimeout, Encoding encoding)
{
try
{
string stringResponse;
var req = (FileWebRequest)WebRequest.Create(uri);
req.Timeout = reqTimeout;
req.Method = WebRequestMethods.File.DownloadFile;
var res = (FileWebResponse)req.GetResponse();
//using (var receiveStream = res.GetResponseStream())
//using (var readStream = new StreamReader(receiveStream,encoding))
//{
// stringResponse = readStream.ReadToEnd();
//}
return stringResponse="0K";
}
catch (WebException webException)
{
throw webException;
}
}
Usage is here:
public dynamic LoadRoomMsg(IAccount account, string roomId)
{
try
{
string uri = string.Format("http://www-pokec.azet.sk/_s/chat/nacitajPrispevky.php?{0}&lok={1}&lastMsg=0&pub=0&prv=0&r=1295633087203&changeroom=1" , account.SessionId, roomId);
var htmlStringResult = HttpFileGetReq(new Uri(uri), ReqTimeout, EncodingType);
//var htmlStringResult = _httpReq.HttpGetReq(new Uri(string.Format("{0}{1}?{2}&lok=", PokecUrl.RoomMsg,account.SessionId,roomId)),
// ReqTimeout, account.Cookies, EncodingType);
if (!string.IsNullOrEmpty(htmlStringResult))
{
return true;
}
return false;
}
catch (Exception exception)
{
throw exception;
}
}
URL on file is here.
I would like read this file to string variable, that’s all. If anyone have some time and can help me I would be very glad to him.
Your URL (http://...) will produce a HttpWebRequest. You can check with the debugger.
Form MSDN:
The FileWebRequest class implements
the WebRequest abstract base class for
Uniform Resource Identifiers (URIs)
that use the file:// scheme to request
local files.
Note the file:// and local files in there.
Tip: Just use the WebClient class.
Rather than implement your own web streams allow the .NET framework to do it all for you with WebClient, for example:
string uri = string.Format(
"http://www-pokec.azet.sk/_s/chat/nacitajPrispevky.php?{0}&lok={1}&lastMsg=0&pub=0&prv=0&r=1295633087203&changeroom=1",
account.SessionId,
roomId);
System.Net.WebClient wc = new System.Net.WebClient();
string webData = wc.DownloadString(uri);
...parse the webdata response here...
Looking at the response from the URL you posted:
{"reason":0}
parsing that should be a simple task with a little string manipulation.
Change FileWebRequest and FileWebResponse to HttpWebRequest and HttpWebResponse.
It doesn't matter that what you're downloading may be a file; as far as the .NET Framework is concerned, you're just retrieving a page from a website.
FileWebRequest is for file:// protocols. Since you're using an http:// url, you want to use HttpWebRequest.
public string HttpFileGetReq(Uri uri, int reqTimeout, Encoding encoding)
{
string stringResponse;
var req = (HttpWebRequest)WebRequest.Create(uri);
req.Timeout = reqTimeout;
var res = (HttpWebResponse)req.GetResponse();
using (var receiveStream = res.GetResponseStream())
{
using (var readStream = new StreamReader(receiveStream,encoding))
{
return readStream.ReadToEnd();
}
}
}
I have a table in my database which contains the URLs of some websites. I have to open those URLs and verify some links on those pages. The problem is that some URLs get redirected to other URLs. My logic is failing for such URLs.
Is there some way through which I can pass my original URL string and get the redirected URL back?
Example: I am trying with this URL:
http://individual.troweprice.com/public/Retail/xStaticFiles/FormsAndLiterature/CollegeSavings/trp529Disclosure.pdf
It gets redirected to this one:
http://individual.troweprice.com/staticFiles/Retail/Shared/PDFs/trp529Disclosure.pdf
I tried to use following code:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Uris);
req.Proxy = proxy;
req.Method = "HEAD";
req.AllowAutoRedirect = false;
HttpWebResponse myResp = (HttpWebResponse)req.GetResponse();
if (myResp.StatusCode == HttpStatusCode.Redirect)
{
MessageBox.Show("redirected to:" + myResp.GetResponseHeader("Location"));
}
When I execute the code above it gives me HttpStatusCodeOk. I am surprised why it is not considering it a redirection. If I open the link in Internet Explorer then it will redirect to another URL and open the PDF file.
Can someone help me understand why it is not working properly for the example URL?
By the way, I checked with Hotmail's URL (http://www.hotmail.com) and it correctly returns the redirected URL.
This function will return the final destination of a link — even if there are multiple redirects. It doesn't account for JavaScript-based redirects or META redirects. Notice that the previous solution didn't deal with Absolute & Relative URLs, since the LOCATION header could return something like "/newhome" you need to combine with the URL that served that response to identify the full URL destination.
public static string GetFinalRedirect(string url)
{
if(string.IsNullOrWhiteSpace(url))
return url;
int maxRedirCount = 8; // prevent infinite loops
string newUrl = url;
do
{
HttpWebRequest req = null;
HttpWebResponse resp = null;
try
{
req = (HttpWebRequest) HttpWebRequest.Create(url);
req.Method = "HEAD";
req.AllowAutoRedirect = false;
resp = (HttpWebResponse)req.GetResponse();
switch (resp.StatusCode)
{
case HttpStatusCode.OK:
return newUrl;
case HttpStatusCode.Redirect:
case HttpStatusCode.MovedPermanently:
case HttpStatusCode.RedirectKeepVerb:
case HttpStatusCode.RedirectMethod:
newUrl = resp.Headers["Location"];
if (newUrl == null)
return url;
if (newUrl.IndexOf("://", System.StringComparison.Ordinal) == -1)
{
// Doesn't have a URL Schema, meaning it's a relative or absolute URL
Uri u = new Uri(new Uri(url), newUrl);
newUrl = u.ToString();
}
break;
default:
return newUrl;
}
url = newUrl;
}
catch (WebException)
{
// Return the last known good URL
return newUrl;
}
catch (Exception ex)
{
return null;
}
finally
{
if (resp != null)
resp.Close();
}
} while (maxRedirCount-- > 0);
return newUrl;
}
The URL you mentioned uses a JavaScript redirect, which will only redirect a browser. So there's no easy way to detect the redirect.
For proper (HTTP Status Code and Location:) redirects, you might want to remove
req.AllowAutoRedirect = false;
and get the final URL using
myResp.ResponseUri
as there can be more than one redirect.
UPDATE: More clarification regarding redirects:
There's more than one way to redirect a browser to another URL.
The first way is to use a 3xx HTTP status code, and the Location: header. This is the way the gods intended HTTP redirects to work, and is also known as "the one true way." This method will work on all browsers and crawlers.
And then there are the devil's ways. These include meta refresh, the Refresh: header, and JavaScript. Although these methods work in most browsers, they are definitely not guaranteed to work, and occasionally result in strange behavior (aka. breaking the back button).
Most web crawlers, including the Googlebot, ignore these redirection methods, and so should you. If you absolutely have to detect all redirects, then you would have to parse the HTML for META tags, look for Refresh: headers in the response, and evaluate Javascript. Good luck with the last one.
Use this code to get redirecting URL
public void GrtUrl(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.AllowAutoRedirect = false; // IMPORTANT
webRequest.Timeout = 10000; // timeout 10s
webRequest.Method = "HEAD";
// Get the response ...
HttpWebResponse webResponse;
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");
webResponse.Close(); // don't forget to close it - or bad things happen
}
}
}
Here's two Async HttpClient versions:
Works in .Net Framework and .Net Core
public static async Task<Uri> GetRedirectedUrlAsync(Uri uri, CancellationToken cancellationToken = default)
{
using var client = new HttpClient(new HttpClientHandler
{
AllowAutoRedirect = false,
}, true);
using var response = await client.GetAsync(uri, cancellationToken);
return new Uri(response.Headers.GetValues("Location").First();
}
Works in .Net Core
public static async Task<Uri> GetRedirectedUrlAsync(Uri uri, CancellationToken cancellationToken = default)
{
using var client = new HttpClient();
using var response = await client.GetAsync(uri, cancellationToken);
return response.RequestMessage.RequestUri;
}
P.S. handler.MaxAutomaticRedirections = 1 can be used if you need to limit the number of attempts.
After reviewing everyone's suggestions I kind of figured this out for at least my case which basically did 3 loops once to https and second one to actual ending location.
This is a recursive function call here:
public static string GrtUrl(string url, int counter)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
string ReturnURL = url;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.AllowAutoRedirect = false; // IMPORTANT
webRequest.Timeout = 10000; // timeout 10s
webRequest.Method = "HEAD";
// Get the response ...
HttpWebResponse webResponse;
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"];
ReturnURL = uriString;
if (ReturnURL == url)
{
webResponse.Close(); // don't forget to close it - or bad things happen!
return ReturnURL;
}
else
{
webResponse.Close(); // don't forget to close it - or bad things happen!
if (counter > 50)
return ReturnURL;
else
return GrtUrl(ReturnURL, counter++);
}
}
}
return ReturnURL;
}
You could check the Request.UrlReferrer.AbsoluteUri to see where i came from. If that doesn't work can you pass the old url as a query string parameter?
This code works for me
var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.AllowAutoRedirect = true;
request.ContentType = "application/x-www-form-urlencoded";
var response = request.GetResponse();
//After sending the request and the request is expected to redirect to some page of your website, The response.ResponseUri.AbsoluteUri contains that url including the query strings
//(www.yourwebsite.com/returnulr?r=""... and so on)
Redirect(response.ResponseUri.AbsoluteUri); //then just do your own redirect.
Hope this helps
I had the same problem and after tryin a lot I couldn't get what i wanted with HttpWebRequest so i used web browser class to navigate to first url and then i could get the redirected url !
WebBrowser browser = new WebBrowser();
browser.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(this.browser_Navigating);
string urlToNavigate = "your url";
browser.Navigate(new Uri(urlToNavigate));
then on navigating you can get your redirected url. Be careful that the first time browser_Navigating event handler occurs, e.url is the same url you used to start browsing so you can get redirected url on the second call
private void browser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
Uri uri = e.Url;
}
This code worked for me with Unicode support:
public static string GetFinalRedirect(string url)
{
try
{
var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.AllowAutoRedirect = true;
request.ContentType = "application/x-www-form-urlencoded";
var response = request.GetResponse();
return response.ResponseUri.AbsoluteUri.ToString();
}
catch(Exception ax)
{
return "";
}
}
string url = ".......";
var request = (HttpWebRequest)WebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
string redirectUrl = response.ResponseUri.ToString();
A way to deal with javascript redirect is to view the source code of the initial domain's page that would load and then extract a new domain aka the final domain directly from the source code. Since it is a javascript redirect then the new domain aka final domain should be there. Cheers
Code to extract the URL address from page source:
string href = "";
string pageSrc = "get page source using web client download string method and place output here";
Match m = Regex.Match(pageSrc, #"href=\""(.*?)\""", RegexOptions.Singleline);
if (m2.Success){
href = m.Groups[1].Value; /* will result in http://finalurl.com */
}
I made this method using your code and it returns the final redirected URL.
public string GetFinalRedirectedUrl(string url)
{
string result = string.Empty;
Uri Uris = new Uri(url);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Uris);
//req3.Proxy = proxy;
req.Method = "HEAD";
req.AllowAutoRedirect = false;
HttpWebResponse myResp = (HttpWebResponse)req.GetResponse();
if (myResp.StatusCode == HttpStatusCode.Redirect)
{
string temp = myResp.GetResponseHeader("Location");
//Recursive call
result = GetFinalRedirectedUrl(temp);
}
else
{
result = url;
}
return result;
}
Note: myResp.ResponseUri does not return the final URL